Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 962
cala Avatar asked Jan 16 '14 21:01

cala


4 Answers

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()" />
`
like image 181
rboling Avatar answered Nov 16 '22 21:11

rboling


You need to use the maxlength attribute for input fields, something like this should do it:

<input name="myTextInput" type="text" maxlength="5"></input>
like image 38
njfife Avatar answered Nov 16 '22 22:11

njfife


You can use "maxlength" attribute to not allow more than x characters & do validation using javascript for min length.

see this example: http://jsfiddle.net/nZ37J/

HTML

<form id="form_elem" action="/sdas" method="post">
   <input type="text" id="example" maxlength="10"></input>
   <span id="error_msg" style="color:red"></span>
   <input type="button" id="validate" value="validate"></input>
</form>

Javascript:

$("#validate").click(function(){
    var inputStr = $("#example").val();
    if(inputStr.length<5)
        $("#error_msg").html("enter atleast 5 chars in the input box");
    else
        $("#form_elem").submit();      
})
like image 3
hemanth Avatar answered Nov 16 '22 21:11

hemanth


I did a bit of a mix of the samples above trying to make it as simple as possible and avoid unnecessary alerts. Script:

function checkLength(){
    var textbox = document.getElementById("comment");
    if(textbox.value.length <= 500 && textbox.value.length >= 5){
        return true;
    }
    else{
        alert("Your comment is too short, please write more.");
        return false;
    }
}

code in the form field would be: onsubmit="return checkLength();">

And the text area in the form itself:

<label for="comment">*Comment:</label>
<textarea name="comment" id="comment" rows="4" cols="40" required="required"></textarea>

hope this helps!

like image 3
Marc F Avatar answered Nov 16 '22 20:11

Marc F