jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了MVC 4自定义数据注释手动jquery验证调用大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我们正在尝试使用MVC 4数据注释创建一些自定义验证,我们创建的验证是一种消息提示而不是限制性验证.
首先,我们创建了一些继承自ValidationAttribute的自定义验证类
 类和重写IsValid()方法来测试数据并返回ValidationResult(如果无效).
显示此数据的视图具有使用EditorTemplates显示剃刀生成的数据的部分视图,使用我们的自定义数据注释和许多内置验证,所有这些都包含在这样的表单中

@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()似乎没有做任何事情,似乎唯一的调用似乎触发了表单验证
$(“形式”).有效的()
但这似乎只显示内置验证,如[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日:如果您使用R_917_11845@VC 4,则需要引用Sy@L_607_45@.web.mvc 3.0以使用IClientValidatable,因为ModelClientValidationRule似乎在MVC 4中不存在

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或partialview中,您必须确保它不在$(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");

如果你想在没有回发或初始页面加载的情况下验证表单,那么似乎只需要jQuery验证器的东西,为此你只需要调用$(‘form’).valid()

希望这有助于某人:)

大佬总结

以上是大佬教程为你收集整理的MVC 4自定义数据注释手动jquery验证调用全部内容,希望文章能够帮你解决MVC 4自定义数据注释手动jquery验证调用所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。