Reputation: 2352
I have two fields "Price From" and "Price To" + "Currency Unit'.
I want to make sure that: - if "From" and "To" both have values, then "Price To" should be ">" "Price From". - if "any" of "Price To" or "Price From" has a value, to make "Currency Unit" required.
Can this be achieved in a custom validator? If yes, where do I place it, on which field? Or could it be possible I create a model-level validator to run on client and server sides?
Thanks
Upvotes: 0
Views: 400
Reputation: 2086
There's a nice example here which you'll have to slightly adapt, but essentialy I think this is the technique you are looking for, which is both client and server validation.
Upvotes: 1
Reputation: 15404
You can handle the validation in the model as model-level validation by specifying the IValidatableObject
interface, and defining the required Validate()
method, like this:
public class Address : IValidatableObject
{
public int PriceTo { get; set; }
public int PriceFrom { get; set; }
public int CurrencyUnit { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if(PriceFrom != null && PriceTo != null)
{
if( ! PriceTo > PriceFrom )
{
results.Add (new ValidationResult("\"Price To\" must be greater than \"Price From\"", new List<string> { "PriceTo", "PriceFrom" }));
}
}
if(PriceFrom != null || PriceTo != null)
{
if(CurrencyUnit == null)
{
results.Add (new ValidationResult("If you indicate any prices, you must specify a currency unit"", new List<string> { "CurrencyUnit" }))
}
}
return results;
}
}
NOTE, however: I don't think your MVC client-side validation picks up this rule, so it will only apply server-side.
Upvotes: 1