maxlength – Javascript len function

maxlength – Javascript len function

Use the logical OR operator to test both conditions.

if (msglen < 4 || msglen > 250) {
    $(#msg).addClass(error);
} else {
    $(#msg).removeClass(error);
}

Theres no need for an else if condition. If its 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:

$(#msg).toggleClass(error, msglen < 4 || msglen > 250);

A truthy value passed as the second argument will add the class. A falsey value will remove it.

Id write it like this:

var msgval = $(#msg).val(),
    msglen = msgval.length,
    notValid = msgval.length < 4 || msgval.length > 250;
$(#msg).toggleClass(error, notValid);

or you could always set the maxlength property of the textbox to 250 and then you dont have to worry about the length exceeding 250 characters. 🙂

maxlength – Javascript len function

if(msglen < 4) {
  $(#msg).addClass(error);
}

Adds the class error

else if(msglen <= 250){
  $(#msg).removeClass(error);
}

Removes it a few lines later..

Why dont you just try this.

if(msglen < 4 || msglen > 250) {
    $(#msg).addClass(error);
}

Leave a Reply

Your email address will not be published.