You can use DataAnnotations to attach validation to objects directly.
Validating with Data Annotation Validators
You can get fancy by creating custom data annotations which will then allow you to create validation on fields of a certain type.
So for your age requirement;
So;
public class IsApplicantOldEnoughAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
DateTime enteredDate = (DateTime)value;
if ((DateTime.Today.Year - enteredDate.Year) >= 14)
return true;
else
return false;
}
}
Your model could then decorate the field;
[IsApplicantOldEnough(ErrorMessage="Applicant must be over 14 years of age")]
[Required]
public DateTime DateOfBirth { get; set; }
Then in your view;
<p>
<label for="UnitPrice">DOB:</label>
<%= Html.TextBox("DateOfBirth")%>
<%= Html.ValidationMessage("DateOfBirth", "*")%>
</p>
Then your Controller could look like this;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Apply([Bind(Exclude = "Id")]Applicant newApplicant)
{
if (!ModelState.IsValid)
return View();
return RedirectToAction("Success");
}
This is a bit more work but you no longer need to call a method yourself everytime you wanted to validate some data.
It also means that all applications that use this model will apply the same business rule to your ages thus providing consistency across the organisation.
I actually happened to have the above handy to some respect. I use it a lot in my objects. Do remember to wrap this in a Try / Catch.