简体   繁体   English

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

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

I am using the jquery validation plugin from: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ 我使用的是jquery验证插件: http//bassistance.de/jquery-plugins/jquery-plugin-validation/

How can I add a regex check on a particular textbox? 如何在特定文本框中添加正则表达式检查?

I want to check to make sure the input is alphanumeric. 我想检查以确保输入是字母数字。

Define a new validation function, and use it in the rules for the field you want to validate: 定义新的验证函数,并在要验证的字段的规则中使用它:

$(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.");

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

Not familiar with jQuery validation plugin, but something like this should do the trick: 不熟悉jQuery验证插件,但这样的事情应该可以解决问题:

var alNumRegex = /^([a-zA-Z0-9]+)$/; //only letters and numbers
if(alNumRegex.test($('#myTextbox').val())) {
    alert("value of myTextbox is an alphanumeric string");
}

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

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