jquery - MVC 4 自定义数据注解手动jquery验证调用

标签 jquery asp.net-mvc c#-4.0 data-annotations

我们正在尝试使用 MVC 4 数据注释创建一些自定义验证,我们正在创建的验证是一种消息提示,而不是限制性验证。 首先我们创建了一些继承自 ValidationAttribute 的自定义验证类 类并重写 IsValid() 方法来测试数据,如果无效则返回 ValidationResult。 显示此数据的 View 具有部分 View ,这些 View 使用 EditorTemplates 使用我们的自定义数据注释和许多内置验证来显示 Razor 生成的数据,所有这些都包装在这样的表单中

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))

我们的要求是让用户发回数据并部分保存表单,但在任何无效字段上提示他们,因此正在使用 表单提交上的 CSS 类允许像这样的回发

<input type="submit" value="Save" class="cancel"/>

所有这些都工作正常,但我们现在要求在页面加载时显示所有错误消息,直到我尝试为止,我认为这不是问题......

我发现了一些在 $(document).ready 事件中使用 jquery 的示例,这些示例调用了表单有效方法,如下所示

Manual form validation in MVC 3 and JQuery

但这似乎对我们不起作用 $('form').Validate() 似乎没有做任何事情似乎触发表单验证的唯一调用是 $(‘表单’).valid() 但这似乎只显示内置验证,例如 [Required] 属性,并且显示自定义验证消息的唯一方法是使用提交按钮回发表单。

一定有一种方法可以让我的自定义数据注释显示消息,而无需第一次回发页面,对吧? 任何帮助将不胜感激。

最佳答案

好吧,我找到了一种方法来获得我想要的结果,尽管这比我想要/想象的要多一些。 我缺少的东西是我没有在自定义验证类中实现 IClientValidatable,并且必须将自定义验证添加到我尝试过的 jQuery Validator addmethod,但没有在自定义验证类中实现 IClientValidatable,我将快速完成如何让这个工作我假设你已经设置/包含了所有 jQuery 东西

首先创建使用自定义验证属性的简单模型

public class Person
{
    [Required]
    [Display( Name="Name")]
    public string Name { get; set; }
    public int Age { get; set; }

    //Uses a custom data annotation that requires that at lease it self or the property name passed in the constructor are not empty
    [OneOfTwoRequired("Mobile")]
    public string Phone { get; set; }
    [OneOfTwoRequired("Phone")]
    public string Mobile { get; set; }
}

自定义验证类,使用反射来获取传入测试的字符串名称的属性

注意截至 2012 年 8 月 15 日:如果您使用 MVC 4,则需要引用 System.web.mvc 3.0 才能使用 IClientValidatable,因为 MVC 4 中似乎不存在 ModelClientValidationRule

public class OneOfTwoRequired : ValidationAttribute, IClientValidatable
    {
        private const string defaultErrorMessage = "{0} or {1} is required.";

        private string otherProperty;

        public OneOfTwoRequired(string otherProperty)
            : base(defaultErrorMessage)
        {
            if (string.IsNullOrEmpty(otherProperty))
            {
                throw new ArgumentNullException("otherProperty");
            }

            this.otherProperty = otherProperty;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessageString, name, otherProperty);
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty);

            if (otherPropertyInfo == null)
            {
                return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty));
            }

            var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

            if (otherPropertyValue == null && value == null)
            {
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            }

            return ValidationResult.Success;
        }
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                //This is the name of the method aaded to the jQuery validator method (must be lower case)
                ValidationType = "oneoftworequired"
            };

        }
    }

将其添加到 View 或部分 View 中,您必须确保它不在 $(document).ready 方法中

    jQuery.validator.addMethod("oneoftworequired", function (value, element, param) {
        if ($('#Phone).val() == '' && $('#Mobile).val() == '')
            return false;
        else
            return true;
    });

    jQuery.validator.unobtrusive.adapters.addBool("oneoftworequired");

如果您想在不回发或在初始页面加载时验证表单并且只需调用 $('form').valid() 来验证表单,则似乎只需要 jQuery 验证器

希望这对某人有帮助:)

关于jquery - MVC 4 自定义数据注解手动jquery验证调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11931987/

相关文章:

c# - 如何为 ASP.NET Core 2 中的所有 Razor 页面添加 .html url 后缀?

jquery - clearInterval(timerId) 不起作用

jquery - 在 Jquery 中将 div 移动到新子级中

javascript - 获取没有滚动条宽度的div宽度

javascript - 如何在 MVC 5 中用 "a"标签替换 ActionLink?

c# - DhtmlX 甘特图未获得正确的链接目标 ID

c#-4.0 - 使用SaveChanges和ExecuteStoreCommand的事务性操作

c# - 为什么协变和逆变不支持值类型

asp.net - 单击按钮时触发的所有页面级事件是什么?

javascript - 每次单击复选框时,弹出窗口都会一致显示