0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hello Faust, thanks for this, I still need to try it. I always thought I can only validate properties and not whole model. Is there a way to add client side validation?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.