简体   繁体   English

jQuery验证程序:表单拒绝验证

[英]jQuery validator: Form refuses to validate

I have a simple Javascript file that needs to run. 我有一个需要运行的简单Javascript文件。 I know it is rendered fine, as the input masking portion works perfectly. 我知道它可以很好地渲染,因为输入遮罩部分可以完美地工作。 However, the form will not validate when I input information. 但是,当我输入信息时,该表格将无法生效。 If I for example put in a phone number 4 digits log, then check for validation, it returns 'true'. 例如,如果我输入4位数的电话号码日志,然后检查验证,则返回“ true”。 It does not use unobtrusive validation. 它不使用不打扰的验证。 The project is a simple ASP.NEt MVC website written on a Visual Studio Enterprise 2015 platform. 该项目是在Visual Studio Enterprise 2015平台上编写的简单ASP.NEt MVC网站。 The page in question on the website is the EditInfo page, for your reference. 网站上有问题的页面是EditInfo页面,供您参考。 There must be some variable I need to set to get this working, but I do not know what it is. 我必须设置一些变量才能使其正常工作,但我不知道它是什么。 Thanks for your help and have a great day. 感谢您的帮助,祝您度过愉快的一天。

First, here is the BundleConfig.cs file. 首先,这里是BundleConfig.cs文件。 This portion (not the whole file) is the jquery.validate plug-in. 这部分(不是整个文件)是jquery.validate插件。

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/additional-methods.js",
                    "~/Scripts/additional-methods.min.js",
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.selectric.js",
                    "~/Scripts/jquery.validate.min.js"));

The bundle is rendered in the layout page. 捆绑包将在布局页面中呈现。

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

The app.js file contains functions used in error placement as well as the jquery.validator default settings. app.js文件包含用于错误放置的函数以及jquery.validator的默认设置。

if ($.validator) {
jQuery.validator.setDefaults({
    invalidHandler: function (form, validator) {

        if (!validator.numberOfInvalids())
            return;

        $('html, body').animate({
            scrollTop: $(validator.errorList[0].element).offset().top - 150
        }, 'fast');

        $(validator.errorList[0].element).focus();

    },
    onkeyup: false
});
}
//
// Name:  errorPlacementValidator
// Description:  Used by the validator.
//
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());
}
}

//
// Name:  highlight
// Description:  Used by the validator to show the error messages.
//
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>");
    }
}
}

//
// Name:  unhighlightValidator
// Description:  Used by the validator to hide the error messages.
//
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");
}
}

Here is the EditInfo.cshtml file script section. 这是EditInfo.cshtml文件脚本部分。

@section scripts {   
@Scripts.Render("~/bundles/jqueryval")
<script src="@Url.Content("~/Scripts/EditInfo.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/app.js")" type="text/javascript"></script>
}

The section scripts is rendered in the layout file. 部分scripts在布局文件中呈现。

@RenderSection("scripts", required: false)

Next, the EditInfo.cshtml page. 接下来,进入EditInfo.cshtml页面。 Here is a sample, with the first item, in this case a text box. 这是一个带有第一项的示例,在本例中为文本框。 The form tag is closed at the end, with no inputs being left out. 表单标签最后关闭,没有输入遗漏。 The javascript file does use the names and not id's for elements. javascript文件确实使用名称而不是id作为元素。

<div class="frontpage">
<form class="form-horizontal" id="frmEditInfo" name="frmEditInfo">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                <label for="workCell" class="col-sm-4 control-label">Work Cellphone</label>
                <div class="col-sm-6">
                    <input type="tel" name="workCell" id="workCell" class="form-control" placeholder="Work Cellphone">
                </div>
            </div>
        </div>

Finally, here is the actual javascript file, EditInfo.js 最后,这是实际的javascript文件EditInfo.js

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

$("#frmEditInfo").validate({
    ignore: [],
    rules: {
        personalEmail:{
            email: true
            //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: {
            email: true
            //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
        },
        workCell: {
            required: true,
            phoneUS: true
            //pattern: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/
        },
        personalCell: {
            phoneUS: true
            //pattern: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/
        },
        otherPhone: {
            phoneUS: true
            //pattern: /^\(?\d{3}\)?\s?-?\d{3}\s?-?\d{4}$/
        }
    },
    messages: {
        personalEmail: {
            email: "Invalid Email"
        },
        otherEmail: {
            email: "Invalid Email"
        },
        workCell: {
            phoneUS: "Invalid Phone Number"
        },
        personalCell: {
            phoneUS: "Invalid Phone Number"
        },
        otherPhone: {
            phoneUS: "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);
    }


});

$('#workCell').inputmask("(999) 999-9999");
$('#personalCell').inputmask("(999) 999-9999");
$('#otherPhone').inputmask("(999) 999-9999");
});

EDIT: Removed unnecessary code regarding submit function. 编辑:删除了有关提交功能的不必要的代码。

I fixed it. 我修好了它。 TL;DR The js file wasn't correctly added in BundleConfig.cs TL; DR js文件未在BundleConfig.cs正确添加

After a lot of research, I put the code into jsfiddle, and it worked. 经过大量研究,我将代码放入jsfiddle中,并且可以正常工作。 So I went back and made sure I had updated JS files and such. 因此,我回过头来确保已更新了JS文件等。 Eventually I found the problem, which was in the BundleConfig file. 最终,我发现了问题所在,该问题在BundleConfig文件中。 The bundle that included the jquery-validate.js file was named incorrectly. 包含jquery-validate.js文件的捆绑包的名称错误。 That is not to say that it was the only issue, Sparky helped me with my rules (not writing my own regex), not using method.min.js file when I was also using method.js . 这并不是说这是唯一的问题,Sparky帮助我制定了规则(不编写自己的正则表达式),同时还使用method.js时不使用method.min.js文件。 I figured I should post the answer just to set the record straight. 我认为我应该发布答案只是为了保持记录。

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

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