javascript 如何将字母数字检查添加到 jQuery 验证插件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6132684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:36:54  来源:igfitidea点击:

How to add alphanumeric check to jQuery validation plugin?

javascriptjquery

提问by Jim

This exact question was asked here:

这里提出了这个确切的问题:

using the jquery validation plugin, how can I add a regex validation on a textbox?

使用 jquery 验证插件,如何在文本框上添加正则表达式验证?

But unfortunately the solution posted isn't working for me. I am using the very popular jquery validation plugin, specifically this version:

但不幸的是,发布的解决方案对我不起作用。我正在使用非常流行的 jquery 验证插件,特别是这个版本:

http://jquery.bassistance.de/validate/jquery.validate.js

http://jquery.bassistance.de/validate/jquery.validate.js

I tried adding the custom alphanumeric function (from the above stack overflow question) like so:

我尝试添加自定义字母数字函数(来自上面的堆栈溢出问题),如下所示:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>

<script type="text/javascript">
$(function() {

    $.validator.addMethod("loginRegex", function(value, element) {
        return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
    }, "Username must contain only letters, numbers, or dashes.");

    $("#myForm").validate({
        rules: {
            "login": {
                required: true,
                loginRegex: true,
            }
        },
        messages: {
            "login": {
                required: "You must enter a login name",
                loginRegex: "Login format not valid"
            }
        }
    });

});
</script>

<form method="post" id="myForm">
    <input type="text" name="login" />  
    <input type="submit" value="Go" />  
</form>

If you run this code you can see that it only validates for some type of input, it doesn't validate the input through the custom alphanumeric function. How can this be made to work?

如果您运行此代码,您可以看到它仅针对某种类型的输入进行验证,而不会通过自定义字母数字函数验证输入。如何使之生效?

回答by ScottE

Could it be that you have an extra comma after your login rule? IE will have trouble with this:

是不是您的登录规则后面多了一个逗号?IE 会遇到这个问题:

rules: {
    "login": {
        required: true,
        loginRegex: true,
    }
},

should be:

应该:

rules: {
    "login": {
        required: true,
        loginRegex: true
    }
},