jquery 使用插件进行名称验证
jquery name validation using plugin
我正在尝试验证用户的名字,使其只接受字符。我也想分配一个最大长度验证,名字不能为空
但我只能对字符进行验证。现在我想为名字设置最大长度,并且当验证失败时,名字也不能为空,它应该将输入框的边框颜色更改为红色并给出错误消息。
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
});
$('#myForm').validate({
rules: {
firstName: {
lettersonly: true
}
},
messages:{
firstName: {
lettersonly: "please enter characters only",
}
}
});
});
.error{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js"></script>
<form id="myForm">
<label for="firstname" id="label1">firstName:</label>
<input type="text"id="firstName" name="firstName"><br><br>
</form>
您可以使用 jquery-验证插件中的内置函数。
https://jqueryvalidation.org/maxlength-method/
Return false if the element is
- some kind of text input and its value is too long
- a set of checkboxes that has too many boxes checked
- a select and has too many options selected
$('#myForm').validate({
rules: {
firstName: {
lettersonly: true
required: true,
maxlength: 200
}
},
messages:{
firstName: {
lettersonly: "please enter characters only",
required: "Enter your first name, please.",
maxlength: "Funny msg"
}
}
});
我正在尝试验证用户的名字,使其只接受字符。我也想分配一个最大长度验证,名字不能为空
但我只能对字符进行验证。现在我想为名字设置最大长度,并且当验证失败时,名字也不能为空,它应该将输入框的边框颜色更改为红色并给出错误消息。
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
});
$('#myForm').validate({
rules: {
firstName: {
lettersonly: true
}
},
messages:{
firstName: {
lettersonly: "please enter characters only",
}
}
});
});
.error{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js"></script>
<form id="myForm">
<label for="firstname" id="label1">firstName:</label>
<input type="text"id="firstName" name="firstName"><br><br>
</form>
您可以使用 jquery-验证插件中的内置函数。
https://jqueryvalidation.org/maxlength-method/
Return false if the element is
- some kind of text input and its value is too long
- a set of checkboxes that has too many boxes checked
- a select and has too many options selected
$('#myForm').validate({
rules: {
firstName: {
lettersonly: true
required: true,
maxlength: 200
}
},
messages:{
firstName: {
lettersonly: "please enter characters only",
required: "Enter your first name, please.",
maxlength: "Funny msg"
}
}
});