我有一个自定义方法
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Zs]*$/i.test(value);
}, 'Your name may only contain letters');
在这里,我正在修剪空格,并仅用一个替换所有重复的空格。然后,我正在验证以确保只有字母和空间。
是否可以制作它,以便将修剪的value
与表格一起提交,而不是用户输入的内容?
使用subsithandler,您可以在提交表单之前做出任何操作,(form.submit(((
请参阅Beleow工作片段
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Zs]*$/i.test(value);
}, 'Your name may only contain letters');
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5,
lettersandspaces: true
},
"age": {
required: true,
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"age": {
required: "Please, enter your age",
}
},
submitHandler: function (form) { // for demo
var newName = $("#name").val().replace(/s+/g, ' ').trim()
$("#name").val(newName);
$(form).valid();
alert("Name = '"+newName+"'");
// comment return and uncomment form.submit(
return false; //form.submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<label for="name">Name :</label>
<input type="text" name="name" id="name" /><br><br>
<label for="age">Age : </label>
<input type="age" name="age" id="age" /><br><br>
<button type="submit">Submit</button>
</form>
在jQuery中以验证形式。如果要更改值输入名称,请先验证。让尝试:
$('#form').validate({
rules: {
'name': {
normalizer: function(){
return $('#name').val().(/s+/g, ' ').trim();
}
}
}
})