ASP.NET MVC3 模型验证数据注释通过客户端验证执行小于或等于另一个属性的操作

发布于 2024-10-27 05:41:48 字数 1332 浏览 2 评论 0原文

我有一个简单的表单,它使用 ASP.NET MVC 3 不显眼的客户端验证。

该模型看起来有点像这样(出于隐私考虑,名称已更改):

public class MyInputModel
{
    public MyInputModel()
    {
    }

    public MyInputModel(MyViewData viewData)
    {
        ViewData = viewData;
        MaxValueForSize = viewData.MaxSize;
    }

    public int MaxValueForSize { get; set; }


    [RegularExpression("[1-9][0-9]*",ErrorMessage = "The value must be a whole number.")]
    public int Size { get; set; }

    [StringLength(255)]
    [Required]
    public string Description{ get; set; }
}

在我看来,我为 MaxValueForSize 添加了一个隐藏字段,并且我想将输入的 Size 值与小于或等于 MaxValueForSize 属性。

我知道我可以通过覆盖验证属性来完成此服务器端操作,如下所示:

internal class SizeValidAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if(value != null)
        {
            var model = (MyInputModel) validationContext.ObjectInstance;


            if ((int)value > model.MaxValueForSize)
                return new ValidationResult(ErrorMessage);

        }
        return base.IsValid(value, validationContext);
    }
}

但是我想(需要)对此属性进行客户端验证。与 Compare 注释的工作原理类似。

有谁知道有什么方法可以做到这一点?我是否需要以某种方式扩展客户端验证?

感谢您的帮助。

I have a simple form which is using ASP.NET MVC 3 unobtrusive client side validation.

The model looks a bit like this (names changed for privacy):

public class MyInputModel
{
    public MyInputModel()
    {
    }

    public MyInputModel(MyViewData viewData)
    {
        ViewData = viewData;
        MaxValueForSize = viewData.MaxSize;
    }

    public int MaxValueForSize { get; set; }


    [RegularExpression("[1-9][0-9]*",ErrorMessage = "The value must be a whole number.")]
    public int Size { get; set; }

    [StringLength(255)]
    [Required]
    public string Description{ get; set; }
}

In my view I put a hidden field in for MaxValueForSize and I want to compare the entered value for Size to less than or equal to the MaxValueForSize property.

I know I can do this server side by overriding validation attribute like so:

internal class SizeValidAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if(value != null)
        {
            var model = (MyInputModel) validationContext.ObjectInstance;


            if ((int)value > model.MaxValueForSize)
                return new ValidationResult(ErrorMessage);

        }
        return base.IsValid(value, validationContext);
    }
}

However I would like to (need to) have client side validation on this property. Similar to how the Compare annotation works.

Does anyone know of a way to do this? Do I need to extend the client side validation somehow?

Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

等待圉鍢 2024-11-03 05:41:48

看看这篇文章。它解释了如何扩展 ASP.NET MVC 模型验证以支持跨字段验证:

扩展 ASP.NET MVC 的验证
http:// /blogs.msdn.com/b/mikeormond/archive/2010/10/05/extending-asp-net-mvc-s-validation.aspx

Have a look at this article. It explains how to extend the ASP.NET MVC model validation to support cross-field validation:

Extending ASP.NET MVC’s Validation
http://blogs.msdn.com/b/mikeormond/archive/2010/10/05/extending-asp-net-mvc-s-validation.aspx

摇划花蜜的午后 2024-11-03 05:41:48

Robert Harvey 的回答让我走上了正确的道路,但使用 ASP.NET MVC3 可以非常简单地使用以下模式覆盖验证:

public class LessThanOrEqualToPropertyAttribute : ValidationAttribute, IClientValidatable
{
    public string OtherProperty { get; set; }

    public override bool IsValid(object value)
    {
        return true;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);

            var otherValue = propertyInfo.GetGetMethod().Invoke(validationContext.ObjectInstance, null);

            if ((int)otherValue < (int)value)
                return new ValidationResult(ErrorMessage);

        }
        return base.IsValid(value, validationContext);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "lessthanorequaltoproperty",
            ErrorMessage = FormatErrorMessage(ErrorMessage),
        };

        rule.ValidationParameters.Add("otherproperty", OtherProperty);

        yield return rule;
    }
}

从我发现的各种相互冲突的文档中,这一点并不完全清楚。

Robert Harvey's answer put me on the right path but it is possible with ASP.NET MVC3 to quite simply override the validation using the following pattern:

public class LessThanOrEqualToPropertyAttribute : ValidationAttribute, IClientValidatable
{
    public string OtherProperty { get; set; }

    public override bool IsValid(object value)
    {
        return true;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);

            var otherValue = propertyInfo.GetGetMethod().Invoke(validationContext.ObjectInstance, null);

            if ((int)otherValue < (int)value)
                return new ValidationResult(ErrorMessage);

        }
        return base.IsValid(value, validationContext);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "lessthanorequaltoproperty",
            ErrorMessage = FormatErrorMessage(ErrorMessage),
        };

        rule.ValidationParameters.Add("otherproperty", OtherProperty);

        yield return rule;
    }
}

This wasn't exactly clear from the various conflicting documentation I found.

樱花细雨 2024-11-03 05:41:48

我知道这已经晚了,但是为了利用 RSL 出色的自我回答,唯一真正缺少的是添加不引人注目的验证适配器的客户端脚本。 此处就是一个很好的例子。

I know this is late, but to piggy back on RSL's excellent self-answer, the only thing really missing was the client script to add an unobtrusive validation adapter. Good example of such over here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文