正则表达式,允许文本之间的空格

时间:2012-10-24 13:03:17

标签: jquery regex jquery-validate

我有以下验证码,其中只过滤字母数字+空格文本......但是在测试两个带空格的字母数字时,它会失败......

$.validator.addMethod("alphaNumeric", function(value, element) {
    $(element).val(value.replace(/^\s+|\s+$/g,''));
    return /^[a-zA-Z0-9 ]*$/.test(value);
}, " AlphaNumeric Only!");

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

您更改了输入值,但它不是您在验证时检查的值:

$.validator.addMethod("alphaNumeric", function(value, element) {
    value = value.replace(/^\s+|\s+$/g,'');
    $(element).val(value); //element.value = value
    return /^(?:(?:[a-zA-Z0-9]+ *)+)$/.test(value);
}, " AlphaNumeric Only!");

我不知道替换/修剪方法应该在验证规则中。但这应该有用。