-1

I want to make custom validation for date where Age is greater than or equal to 18.

Can any one idea with mvc4 with custom validation?

Please let me know if any solution is there..

Regards

user2805091
  • 9
  • 1
  • 6
  • I want to make age validation as from datepicker choosing date...please let me know any one have implemented for custom validation.. – user2805091 Sep 25 '13 at 22:46

1 Answers1

1

Just use a Range validator:

[Range(18, int.MaxValue)]
public int Age { get; set; }

It is available in the System.ComponentModel.DataAnnotations namespace.

UPDATE

For validating a date was at least 18 years ago you can use a custom validation attribute like this:

public class Over18Attribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string message = String.Format("The {0} field is invalid.", validationContext.DisplayName ?? validationContext.MemberName);

        if (value == null)
            return new ValidationResult(message);

        DateTime date;
        try { date = Convert.ToDateTime(value); }
        catch (InvalidCastException e) { return new ValidationResult(message); }

        if (DateTime.Today.AddYears(-18) >= date)
            return ValidationResult.Success;
        else
            return new ValidationResult("You must be 18 years or older.");
    }
}
asymptoticFault
  • 4,491
  • 2
  • 19
  • 24