Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the maximum length of 6 and minimum length of 6 in a textbox? [duplicate]

Consider:

 <input id="groupidtext" type="text" style="width: 100px;" maxlength="6" /></td>

Is there a way to set the minimum length to 6?

like image 356
user259896 Avatar asked May 02 '14 15:05

user259896


3 Answers

You could do it with JavaScript with something like this:

<input onblur="checkLength(this)" id="groupidtext" type="text" style="width: 100px;" maxlength="6" />
<!-- Or use event onkeyup instead if you want to check every character strike -->

function checkLength(el) {
  if (el.value.length != 6) {
    alert("length must be exactly 6 characters")
  }
}

Note this would work in older browsers which don't support HTML 5, but it relies on the user having JavaScript switched on.

like image 56
user2808054 Avatar answered Oct 10 '22 19:10

user2808054


You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters.

Your best bet is to validate the input when the form is submitted to ensure that the length is six.

maxlength is not a validation attribute. It is designed to prevent the user from physically typing in more than six characters. The corresponding minlengh is not in scope of the HTML specification, because its implementation would render the textbox unusable.

like image 35
Xpanse Avatar answered Oct 10 '22 19:10

Xpanse


You can use the HTML5 pattern attribute or use JavaScript.

The pattern could look for example like this:

<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />

But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.

As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.

like image 44
Alex Avatar answered Oct 10 '22 20:10

Alex