The model looks like this, with no attributes:
public class PersonalModel : Validatable
{
public string Name { get; set; }
public string Email { get; set; }
public override void Validate(dynamic item)
{
if (this.ValidatesPresenceOf(item.Name, "Name is required"))
{
if (((String)item.Name).Length > 5)
{
Errors.Add("name is too long less than 5 chars please!");
}
}
}
}
and the action looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PersonalInfo(PersonalModel model)
{
if (model.IsValid(model))
{
this.FlashInfo("Your Personal info was successfully received");
return RedirectToAction("ThankYou");
}
else
{
ModelState.AddModelError(string.Empty, String.Join("; ", model.Errors.ToArray())) ;
return View(model);
}
}
This is the baseclass Validatable
:
public class Validatable : DynamicObject
{
//Hooks
public virtual void Validate(dynamic item) { }
//Temporary holder for error messages
public IList<string> Errors = new List<string>();
public bool IsValid(dynamic item)
{
Errors.Clear();
Validate(item);
return Errors.Count == 0;
}
//validation methods
public virtual bool ValidatesPresenceOf(object value, string message = "Required")
{
if (value == null || String.IsNullOrEmpty(value.ToString()))
{
Errors.Add(message);
return false;
}
return true;
}
}