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
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
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.");
}
}