Limit number of characters in input

112 views Asked by At

How do I limit the number of characters in my input?

In the following code I want max 14 characters.

<script language='JavaScript'>
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;   
    if((tecla>47 && tecla<58)) return true;
    else{
        if (tecla==8 || tecla==0) return true;
    else  return false;
    }
}
</script>




<input type='text' size='10' value='' onkeypress='return SomenteNumero(event)'>
2

There are 2 answers

0
Brian H On BEST ANSWER

This can be done with html

<input type="text" name="username" maxlength="14">

If you dont trust client side validation:

$maxlength = 14;
$string = $_POST['string'];
if([url=http://us2.php.net/manual/en/function.strlen.php]strlen[/url]($string) > $maxlength) {
$string = [url=http://us2.php.net/substr]substr[/url]($string, 0, $maxlength);
1
Sari Rahal On

You can use HTML maxlength on the input like this:

<input type="text" name="usrname" maxlength="14">