Instead of the below regex:
/^[a-zA-Z]+$/
Use this:
/^[a-zA-Z\s]+$/
This will also take the space.
题
My validation accepts only alphabets. I want allow spaces as well.
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z]+$/);
});
What change needs to be done here?
解决方案
Instead of the below regex:
/^[a-zA-Z]+$/
Use this:
/^[a-zA-Z\s]+$/
This will also take the space.
其他提示
Just leave a space or use \s
in your regex:
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z\s]+$/);
// -- or leave a space here ^^
});
jQuery.validator.addMethod("lettersonlys", function(value, element) {
return this.optional(element) || /^[a-zA-Z ]*$/.test(value);
}, "Letters only please");
Use pattern: /^[a-zA-Z ]*$/
Your validation is proper. You just need to change regex /^[a-zA-Z ]*$/
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z ]*$/);
});
**
I have tried above but space was an issue in above given regex /^[a-zA-Z\s]+$/ and /^[a-zA-Z]+$/. The Below worked for me:
**
$('.name-val').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z ]+$");
var strigChar = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(strigChar)) {
return true;
}
return false
});
Please use these pattern for validation.
var pattern = /^[a-zA-Z ]+$/;
if(!pattern.test(name) && name !=''){
return false;
}