Mike
Mike

Reputation: 371

Limiting number of form characters with Javascript validation

How can I limit the number of characters that an input form allows? I'm using a validation like this

//Last name
var x=document.forms["regForm"]["lname"].value
if (x==null || x=="")
  {
  alert("Last name must be filled out");
  return false;
  }

Upvotes: 0

Views: 2164

Answers (2)

Neil
Neil

Reputation: 55382

Why not set the maxlength attribute (maxLength property) on the <input> element?

Upvotes: 2

Naftali
Naftali

Reputation: 146302

you can do something like this:

<script>

function testInput(obj, max_length){
    if(obj.value.length > max_length){
        alert(obj.name + "'s length is too long");
    }
}

</script>

<input name='lName' onchange='testInput(this, 8);'/>
<input name='fName' onchange='testInput(this, 15);'/>

fiddle: http://jsfiddle.net/maniator/FQTM5/

Upvotes: 0

Related Questions