ASP.NET MVC - one validator on two textfields
I've got an interesting client requirement.
I have a control that needs to be displayed like so:
Date of xxx [ mm ][ yy ]
There is a label with two textfields - one for month in digits and one for year in digits.开发者_如何学运维
Although there are two text fields, we want the validation to run once validating both fields.
Also there are a number of these controls on a page. How would be the best way to package this up so that I can call:
@Laberfor(x => x.Datexxx)
@EditorFor(x => x.Datexxx)
Thanks in advance
If your control is strongly typed, you could implement IValidatableObject
and its Validate
method.
Assuming your model looks like this:
public class CombinedDateViewModel : IValidatableObject
{
[Required]
public int month { get; set; }
[Required]
public int year { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(month > 12 || month < 1)
yield return new ValidationResult("Month is out of range");
if(year < 0 || year > 2020)
yield return new ValidationResult("Year is out of range");
}
}
The yielded validation results will manifest in the validation summary.
精彩评论