Reputation: 61
I want to set the input length of a textbox to 9 characters only. No more, no less. Is there any way to do it? Any help would be very much appreciated. Thanks!
Upvotes: 4
Views: 21694
Reputation: 3125
You can set minlength and maxlenght attributes to the same value in your input.
<input type="text" minlength="9" maxlength="9">
Out of the box the browser will consider only the first 9 characters and prevent you from typing more. Using pattern you can type as many as you want but the validation will fail. Also the validation message has better user experience:
minlength and maxlength:
Please lengthen this text to 9 characters or more (you are currently using 8 characters).
pattern:
Please match the requested format.
Upvotes: 3
Reputation: 1046
this is example -
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>index</title>
</head>
<body>
<script type="text/javascript">
function chkpassword() {
var p1 = document.getElementById("pass").value;
var min = 9
if(p1.length == min) {
alert('ok')
} else{
alert(":( The password must be at least 9 characters long.");
}
}
</script>
<input type=text id=pass name=pass value="" style='width:245px' >
<input type=button id=btnOk name=btnOk value="OK" onclick='chkpassword()' />
</body>
</html>
use this code to get your solution.
Upvotes: 0
Reputation: 15804
With HTML5 you can use the pattern
attribute to do this:
<input type="text" pattern=".{9}" required name="patternTest" title="Field must be 9 characters long" />
Upvotes: 5
Reputation: 103428
var ele = document.getElementById("textboxId");
if (!(ele.value.length==9)){
//throw validation error
}
Upvotes: 3
Reputation: 2879
If it's an input you can use attribute maxlength=9
, of course in this case you can have less than 9, but it would be good to validate it and not send the form in less than 9 and display an error.
If it's a textarea element, you would need javascript to do that
Upvotes: 1