【问题标题】:add regex to jquery.validate将正则表达式添加到 jquery.validate
【发布时间】:2012-11-26 22:56:46
【问题描述】:

需要在我的 jquery.validate 脚本中添加一个正则表达式检查。

我有这个:

$().ready(function() {
  $("#myBlahForm").validate({

    rules: {
        someName: {
            required: true,
            minlength: 5,
            maxlength: 8,
        },
        somePassword: {
            required: true,
                            minlength: 5,
            maxlength: 8,
        },
        someConfirmPassword: {
            required: true,
            equalTo: "#somePassword"
        },
    },
    messages: {
        someName:  {
            required: "Please create your username",
        },
        somePassword: {
            required: "Please create a password",
        },
        someConfirmPassword: {
            required: "Please re-enter your password",
            equalTo:  "Passwords must match"
        },
    }
});

});

当用户在此处输入数据时,我想检查数据库中允许使用的特定字符作为密码:

    <label for="someName">Username</label>
    <input type="text" id="someName" name="someName" placeholder="Create a Username"/>

    <label for="somePassword">Password</label>
    <input type="password" id="somePassword" name="somePassword" placeholder="Create a Password"/>

    <label for="someConfirmPassword">Confirm Password </label>
    <input type="password" id="someConfirmPassword" name="someConfirmPassword" placeholder="Verify your Password"/>

使用来自 bassisstance 的 jquery.validate 插件将正则表达式检查添加到密码或用户名等必填字段的最佳方法是:http://docs.jquery.com/Plugins/Validation

基本上,我需要确保他们创建的密码和用户名只有 0-9、字母和几个特殊字符。

【问题讨论】:

标签: jquery jquery-plugins


【解决方案1】:

好吧,您可以使用addMethod 添加您的自定义验证方法,例如

$.validator.addMethod("regx", function(value, element, regexpr) {          
    return regexpr.test(value);
}, "Please enter a valid pasword.");

还有,

...
$("#myBlahForm").validate({

    rules: {
        somePassword: {
            required: true ,
            //change regexp to suit your needs
            regx: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}$/,
            minlength: 5,
            maxlength: 8
        }
    }

【讨论】:

    【解决方案2】:
    required: function(element){
        return /[a-zA-Z0-9]/.test($('#someConfirmPassword').val());
    }
    

    如果正则表达式通过,上述表达式将返回 true,否则返回 false。更改它以满足您的需求。

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      相关资源
      最近更新 更多