I’ve got a function which validate the length of the value of a field,
function validateName(name) {
if(name.val().length < 5) {
}
}
I want to check also for the presence of white spaces.
I tried with this but it didn’t work:
function validateName(name) {
if(name.val().length < 5 && name.val(" ") < 0) {
}
}
The problem in the code above is that
$.fn.valchanges behaviour on the basis of the arguments it receives as input; and specifically, it’s a getter when it’s executed without parameters, and a setter when it’s executed with one parameter.So this line:
doesn’t check for the presence of empty space in the value, but set the value to a single empty space.
There’re numerous different approaches to check if a string contains at least an empty space; here I’ll go for
String#indexOf, so that thevalidateNamefunction can be written as:A more expressive approach would be to use
String#includes, but it’s also less widely supported by browsers.Also, as general advice I wouldn’t mess the validation logic with jQuery; that is, it would be better for
validateNameto accept as input a plain string, not a jQuery object representing the input field.