Search code examples
javascripthtmlinputlimitonkeypress

Limit number of characters in input


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)'>

Solution

  • 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);