MVC 4自定义验证”;无法获取属性'addMethod'&”;

MVC 4 custom validation "Unable to get property 'addMethod'"

本文关键字:属性 addMethod 获取 自定义 验证 MVC      更新时间:2023-09-26

我正在尝试在MVC中实现自定义密码验证。我的服务器端验证工作得很好,但不知道目前如何注册客户端才能工作。

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

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

Webconfig:

<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>

自定义密码验证器.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部分出了问题,不确定为什么添加验证会如此复杂。

谢谢你的帮助!-Idan

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