I'm trying to validate using jQuery Validator if input only contains spaces, and allow space only if there's a letter inside it.
Note that it should also display error if name contains numbers. Allow only the space if it starts with a letter.
This is what I have so far that only allows letters and spaces:
jQuery.validator.addMethod("letterswithspace", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "letters only");
Also tried this one but it trims the string and can't add a space between names:
first_name : {
letterswithspace : true,
required: {
depends:function(){
$(this).val($.trim($(this).val()));
return true;
}
}
}
You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.
A more accurate wording for \W is any Non-Alphanumeric character. \s is for Any Whitespace. Show activity on this post. \W means "non-word characters", the inverse of \w , so it will match spaces as well.
You can match a space character with just the space character; [^ ] matches anything but a space character.
To match the terms:
You need to use this regex expression:
/^[a-z][a-z\s]*$/
So in your js it should be:
jQuery.validator.addMethod("letterswithspace", function(value, element) {
return this.optional(element) || /^[a-z][a-z\s]*$/i.test(value);
}, "letters only");
Explanation
^[a-z]
means start with one letter[a-z\s]*$
means after accept zero or more letters or spacesValid sentence
If you want a valid sentence structure:
use:
/^([a-z]+\s)*[a-z]+$/
By the way
a-z
use a-zA-Z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With