0

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;
  }

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

2 Comments

Is there anyway it can look similar to the code I've entered?
@Mike where do you put your code, is it in any onchange (or any action) call?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.