0

我有两个字段“Price From”和“Price To”+“Currency Unit”。

我想确保: - 如果“From”和“To”都有值,那么“Price To”应该是“>”“Price From”。- 如果“Price To”或“Price From”中的“any”具有值,则需要“Currency Unit”。

这可以在自定义验证器中实现吗?如果是,我应该把它放在哪里,在哪个字段上?或者我是否有可能创建一个模型级验证器以在客户端和服务器端运行?

谢谢

4

2 回答 2

1

IValidatableObject您可以通过指定接口并定义所需的方法来将模型中的验证作为模型级验证来 Validate()处理,如下所示:

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.

于 2012-08-09T22:57:26.203 回答
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.

于 2012-08-09T23:02:15.573 回答