Peter Susko
Peter Susko

Reputation: 139

Javascript len function

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?

Upvotes: 0

Views: 946

Answers (3)

pete
pete

Reputation: 25081

I'd 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 don't have to worry about the length exceeding 250 characters. :)

Upvotes: 1

I Hate Lazy
I Hate Lazy

Reputation: 48761

Use the logical OR operator to test both conditions.

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

There's no need for an else if condition. 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:

$("#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.

Upvotes: 2

Aesthete
Aesthete

Reputation: 18848

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

Adds the class error

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

Removes it a few lines later..

Why don't you just try this.

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

Upvotes: 0

Related Questions