简体   繁体   English

Javascript-jQuery验证插件规则方法不起作用

[英]Javascript - jQuery Validate plugin rules method not working

I have a simple javascript file that just needs to run the rules method. 我有一个简单的javascript文件,只需要运行rules方法。 Unfortunately, it is not working for some reason. 不幸的是,由于某种原因,它无法正常工作。 I know my custom javascript file is being rendered fine as the input masking is working fine. 我知道我的自定义JavaScript文件可以很好地呈现,因为输入蒙版可以正常工作。 I have double checked to make sure I have the jquery validate script being rendered, so I am unsure as to what my problem is. 我已仔细检查以确保呈现了jquery validate脚本,因此我不确定我的问题是什么。 The project is a simple mvc website written on a Visual Studio Enterprise 2015 platform. 该项目是在Visual Studio Enterprise 2015平台上编写的简单mvc网站。 The page in question on the website is the EditInfo page, for your reference. 网站上有问题的页面是EditInfo页面,供您参考。

Here is the BundleConfig.cs adding the validate bundle. 这是BundleConfig.cs,它添加​​了验证包。

public static void RegisterBundles(BundleCollection bundles)
    {
     //More bundles obviously are added
      bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));
    }

Next, here is the Layout file, where the script is rendered. 接下来,这是布局文件,在此处渲染脚本。

@Scripts.Render("~/bundles/jqueryval")

Next, here are the 2 custom javascript files declared in the view. 接下来,这是在视图中声明的2个自定义javascript文件。

    <script src="@Url.Content("~/Scripts/EditInfo.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/app.js")" type="text/javascript"></script>

Then, here is the EditInfo custom javascript file that uses the validate method. 然后,这是使用validate方法的EditInfo自定义javascript文件。 This is the whole file, minus the 3 lines regarding input masking that work fine. 这是整个文件,减去有关输入屏蔽的3行代码即可正常工作。

$(document).ready(function () {
var counter = 0;
var $CreateProfilevalidator = {};


$CreateProfilevalidator = $("#frmEditInfo").validate({
    rules: {
        personalEmail:/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i,
        otherEmail: /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i,
        workCell: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/,
        personalCell: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/,
        otherPhone: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/
    },
    messages: {
        personalEmail: "Invalid Email",
        otherEmail: "Invalid Email",
        workCell: "Invalid Phone Number",
        personalCell: "Invalid Phone Number",
        otherPhone: "Invalid Phone Number"
    },
    errorPlacement: function (error, element) {
        errorPlacementValidator(error, element);
    },
    highlight: function (element, errorClass, validClass) {
        counter++;
        highlightValidator(element, errorClass, validClass, counter);
    },
    unhighlight: function (element, errorClass, validClass) {
        counter++;
        unhighlightValidator(element, errorClass, validClass, counter);
    }

});
});

Finally, here is the app.js file that contains the 3 validator methods used in my javascript file. 最后,这是app.js文件,其中包含我的javascript文件中使用的3个验证器方法。

function errorPlacementValidator(error, element) {
if (element.is(":radio")) {
    error.appendTo(element.closest("[class*='col-sm-']"));
}
else if (element.parents('.selectric-wrapper').size() > 0) {
    console.log('selectric error');
    error.appendTo(element.closest('[class*="col-sm-"]'));
}
else {
    error.appendTo(element.parent());
}
}

function highlightValidator(element, errorClass, validClass, counter) {
var $parent = $(element).parent();

// remove icon and success spans if any
$parent.find("span.form-control-feedback, span.sr-only").remove();

// add ".error" class to input element
$(element).addClass(errorClass).removeClass(validClass);

// add Bootstrap ".has-error" class to parent div.form-group element
$(element).closest(".form-group").removeClass("has-success").addClass("has-error has-feedback");

// need to have it check to see if span already added
// only add for non radio or non select input elements
if (!$(element).is(":radio, select, textarea, :checkbox, .btn") && !$(element).hasClass("datepicker")) {
    counter++;

    var $spans = $parent.find("span");

    // check to make sure error spans are not already in form-group before attempting to append after input
    if ($spans.length == 0) {
        // add span element with ".glyphicon" ".glyphicon-remove" ".form-control-feedback" classes after input
        $(element).after("<span class='glyphicon glyphicon-remove form-control-feedback' aria-hidden='true'></span>");
        $(element).after("<span id='inputError" + counter + "Status'" + " class='sr-only'>(error)</span>");
    }
}
}

function unhighlightValidator(element, errorClass, validClass, counter) {
var $parent = $(element).parent();

// remove icon and success spans if any
$parent.find("span.form-control-feedback, span.sr-only").remove();

// remove ".error" class from input element
$(element).removeClass(errorClass).addClass(validClass);

if (!$(element).is(":radio, select, textarea, :checkbox, .btn") && !$(element).hasClass("datepicker")) {
    // // remove Bootstrap ".has-error" class from parent div.form-group element
    $(element).closest(".form-group").removeClass("has-error").addClass("has-success has-feedback");

    var $spans = $parent.find("span");

    if ($spans.length == 0 && !$(element).is("select")) {
        $(element).after("<span class='glyphicon glyphicon-ok form-control-feedback' aria-hidden='true'></span>");
        $(element).after("<span id='inputSuccess" + counter + "Status'" + " class='sr-only'>(error)</span>");
    }
} else if ($(element).parents('.selectric-wrapper').size() > 0) {
    $(element).closest(".form-group").removeClass("has-error").addClass("has-success has-feedback");
}
}

I have googled and done my research, but the cause still escapes my grasp. 我已经用谷歌搜索并完成了研究,但是原因仍然没有得到我的掌握。 If I have left out any important information, I apologize. 如果我遗漏了任何重要信息,我深表歉意。 But the site I am writing still will not give an error when I put an improperly formatted email address or shorter than required phone number. 但是,当我输入格式错误的电子邮件地址或短于要求的电话号码时,我正在编写的网站仍然不会出现错误。 Edit: wording 编辑:措辞

The rules object is constructed using a comma-separated list of key: value pairs that represent field names with their methods. rules对象是使用逗号分隔的key: value对列表构成的,这些key: value对表示字段名称及其方法。 Inside of the methods part is another comma-separated list of key: value pairs that represent the method name and its parameter. 方法部分的内部是另一个逗号分隔的key: value列表key: value代表方法名称及其参数的key: value对。 Your attempt is totally missing the actual rules (methods). 您的尝试完全缺少实际的规则(方法)。

$('#yourform').validate({
    rules: {  
        fieldname1: {        // <- field NAME
            required: true,  // <- rule (method) : parameter
            phoneUS: true    // <- rule (method) : parameter
        },
        fieldname2: {        // <- field NAME
            required: true,  // <- rule (method) : parameter
            email: true      // <- rule (method) : parameter
            .....

If you want to validate regex, then you need to use the pattern method that is part of the additional-methods.js file . 如果要验证正则表达式,则需要使用additional-methods.js文件中一部分的pattern方法。

$CreateProfilevalidator = $("#frmEditInfo").validate({
    rules: {
        personalEmail: {
            pattern: /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i
        },
        otherEmail: {
            pattern: /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,15}|[0-9]{1,3})(\]?)$/i
        } 
        ....

Since your list of rules is missing, I also have no idea if you want the field required , etc. But you'd need to list those rules as well. 由于缺少规则列表,因此我也不知道您是否required字段,等等。但是您也需要列出这些规则。

While we're at it, why all the regex? 当我们使用它时,为什么要使用所有正则表达式呢? The plugin already includes various methods for phone numbers and email addresses. 该插件已经包括用于电话号码和电子邮件地址的各种方法。 Refer to the docs and browse the Additional-Methods file. 请参考文档并浏览“其他方法”文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM