niks
niks

Reputation: 1083

Javascript validation for entering text up to maximum length

I have been trying to validate a textbox which allows text to be entered up to 128 charecters only. But the code is unable to validate the text if I press the key and hold it without key up, allowing filling of the textbox above 128 chars. The validation works when I key up, popping up the alert. Below is the code.

  (textboxentered.value>128)
  {
    alert("Please enter text upto 128 Charecters");
  }  

What I want is a solution such that when a key is pressed so long without key up, the text box should not allow more than 128 characters.

Upvotes: 2

Views: 2553

Answers (2)

You can use x.length to get the length of the string and compare

if (textboxentered.value.lenght>128)   {
    alert("Please enter text upto 128 Charecters");   
}

Upvotes: -1

dchiang
dchiang

Reputation: 67

Why not just use the maxlength HTML property?

<input type="text" name="textbox" maxlength="128">

Upvotes: 5

Related Questions