I have a form verification that checks for a minimum length, which works fine. However I also need to check for a max length.
I’m using the following code for an textarea field called “msg” to verify minimum lenth, which works fine:
var msgval = $("#msg").val();
var msglen = msgval.length;
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
This works fine, but if I add a similar verification for msglen > 250, it ignores the previous minimum length requirement when structured as such:
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(msglen > 250) {
$("#msg").addClass("error");
}
else if(msglen <= 250){
$("#msg").removeClass("error");
}
How can I combine the two arguments?
Use the logical OR operator to test both conditions.
There’s no need for an
else ifcondition. If it’s not less than 4 and not greater than 250, then you know you can remove the class.Or a shorter version could be written like this:
A truthy value passed as the second argument will add the class. A falsey value will remove it.