How to set min and max character length in a textbox using javascript

cala picture cala · Jan 16, 2014 · Viewed 79.8k times · Source

If I have a text and I only want to allow the user enter text between 5 and 10 characters long, how do I do this using javascipt?

I have tried using mix and max functions but they only works for numeric data.

Answer

rboling picture rboling · Jan 16, 2014

You could do something like this:

`

function checkLength(){
    var textbox = document.getElementById("textbox");
    if(textbox.value.length <= 10 && textbox.value.length >= 5){
        alert("success");
    }
    else{
        alert("make sure the input is between 5-10 characters long")
    }
}
</script>
<input type="text" id="textbox"></input>
<input type="submit" name="textboxSubmit" onclick="checkLength()" />
`