【问题标题】:MVC 4 custom validation "Unable to get property 'addMethod'"MVC 4 自定义验证“无法获取属性‘addMethod’”
【发布时间】:2015-12-10 14:37:06
【问题描述】:

我正在尝试在 MVC 中实现自定义密码验证。 我的服务器端验证工作完美,但无法弄清楚当前如何注册客户端才能工作。

我收到一个错误: "http://localhost:60215/Scripts/CustomPaswwordValidator.js 中第 6 行第 5 列未处理的异常

0x800a138f - JavaScript 运行时错误:无法获取未定义或空引用的属性“addMethod””

网络配置:

<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

型号:

 [CustomPasswordValidator(FirstName = "FirstName", LastName = "LastName")]
    public string Password { get; set; }

查看:

    <div class="form-group">
        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="control-label">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })

        </div>

        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
    </div>

查看脚本加载:

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jquery.validate")


<script src="~/Scripts/MicrosoftMvcValidation.js"></script>

<script src="~/Scripts/CustomPaswwordValidator.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate-vsdoc.js"></script>
<script src="~/Scripts/jquery-1.4.4-vsdoc.js"></script>
<script src="~/Scripts/ jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"   type="text/javascript"></script>
<script src="~/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

CustomPasswordValidator.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UserVerification.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace Custom_DataAnnotation_Attribute.Models
{
    public class CustomPasswordValidator : ValidationAttribute, IClientValidatable
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public CustomPasswordValidator()
            : base("Password client test")
{

}

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage("Password client test");
            rule.ValidationParameters.Add("firstname", FirstName);
            rule.ValidationParameters.Add("lastname", LastName);
            rule.ValidationType = "passwordvalidation";
            yield return rule;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            int requirmentsCount = 0;
            string _LastName, _FirstName;
            Object instance = validationContext.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(FirstName).GetValue(instance, null);
            _FirstName = proprtyvalue.ToString();
             proprtyvalue = type.GetProperty(LastName).GetValue(instance, null);
             _LastName = proprtyvalue.ToString();

            if (value != null)
            {
                string password = value.ToString();
                //CANNOT contain your first or last name
                if (password.ToLower().Contains(_FirstName.ToLower()) || password.ToLower().Contains(_LastName.ToLower()))
                {
                    return new ValidationResult("The password cannot contain your first or last name. Please try again.");
                }
                if (password.Length<8 || password.Length>30)
                {
                    return new ValidationResult("Your password must be between 8 and 30 characters in length. Please try again.");
                }
                //English uppercase characters (A through Z)
                if (password.Any(char.IsUpper))
                {
                    requirmentsCount++;
                }
                //English lowercase characters (a through z)
                if (password.Any(char.IsLower))
                {
                    requirmentsCount++;
                }
                //Base 10 digits (0 through 9)
                if (password.Any(char.IsDigit))
                {
                    requirmentsCount++;
                }
               // Non-alphabetic characters: ~ ! @ # $ % ^ & * _ - + = ` | \ ( ) { } [ ] : ; " ' < > , . ? / SPACE
                if (password.Any(char.IsPunctuation))
                {
                    requirmentsCount++;
                }

                //if (Regex.IsMatch(password, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase))
                //{
                //    return ValidationResult.Success;
                //}
                if (requirmentsCount>2)
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult("Your password does not contain at least 3 different types of characters. Please try again.");
                }
            }
            else
            {
                return new ValidationResult("" + validationContext.DisplayName + " is required");
            }
        }
    }
}}

CustomPasswordValidation.js(只是尝试返回 false 以查看这是否有效):

/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />


jQuery.validator.addMethod("passwordvalidation", function (value, element, param) {
    if (!value) return false;

    var FirstName = param.firstName;
    var LastName = param.lastName;
    window.alert("sometext");



    return false;
});

jQuery.validator.unobtrusive.adapters.add("passwordvalidation", ["firstName", "lastName"], function (options) {
    var params = {
        firstName: options.params.firstName,
        lastName: options.params.lastName,

    };

    options.rules["passwordvalidation"] = params;
    if (options.message) {
        options.messages["passwordvalidation"] = options.message;
    }
});

我很确定 js 部分有问题,不知道为什么添加验证这么复杂。

感谢您的帮助! -伊丹

【问题讨论】:

  • 你有什么错误吗?并在网络配置中添加这个&lt;add key="ClientValidationEnabled" value="true" /&gt; 并尝试
  • 我得到:0x800a138f - JavaScript 运行时错误:无法获取未定义或空引用的属性“addMethod””
  • 您没有将 jquery 验证文件加载到您的视图中
  • 我编辑了帖子,查看视图的脚本部分
  • 不要加载 jquery-1.4.4-vsdoc.js" 并且不要加载两次验证插件

标签: javascript jquery asp.net-mvc validation


【解决方案1】:

我发现了问题,首先我导入了错误版本的 Jquery 文件,而且顺序似乎很重要,不得不玩一下

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多