我正在使用jQuery验证插件来验证表单。我有一个我需要验证的用户名字段。到目前为止,这就是我所拥有的:
$(".personal_form").validate({
errorElement: 'div',
rules: {
username: {
required: true,
maxlength: 15,
remote: {
url: "usernameChecker.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
},
},
},
},
},
messages: {
username: {
required: "Please enter a username",
maxlength: "Your username should not exceed 15 characters.",
remote: "This username is taken."
},
},
});
我想这样做,如果有人输入无效的用户名,它将显示错误。例如,如果有人输入特殊字符:“!@#$%^& *()_ + =〜` - ”它将显示错误。有效的用户名是具有字母或数字的用户名。我怎么能这样做?
答案 0 :(得分:1)
创建自定义验证规则,根据您的规则检查用户名,如:
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9 ]+$/.test(value);
});
并添加验证
答案 1 :(得分:0)
您可以pattern
<input type="text">
元素RegExp
属性\w+|d\+
<label>
来匹配字或数字字符,css
元素,:focus
{{ 1}},:invalid
,:after
#username:focus:invalid + label[for="username"]:after {
content: "input must contain only letters and numbers";
color:red;
}
<input type="text"
pattern="\w+|d\+"
id="username"
placeholder="input letters and numbers" />
<label for="username"></label>
答案 2 :(得分:0)
将其添加到:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
return this.optional(element) || regexp.test(value);
},
"Please provide a valid username."
);
$(".personal_form").validate({
errorElement: 'div',
rules: {
username: {
required: true,
maxlength: 15,
regex: /^[a-zA-Z0-9 ]+$/,
remote: {
url: "usernameChecker.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
},
},
},
},
},
messages: {
username: {
required: "Please enter a username",
maxlength: "Your username should not exceed 15 characters.",
remote: "This username is taken."
},
},
});
答案 3 :(得分:-2)
使用jQuery.validator.addMethod( name, method [, message ] )
对表单字段进行自定义验证。