cala
cala

Reputation: 1421

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.

Upvotes: 9

Views: 97861

Answers (5)

Marc F
Marc F

Reputation: 41

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!

Upvotes: 4

Delbin Thomas
Delbin Thomas

Reputation: 335

<input name="myTextInput" type="text" minlength="5" maxlength="10"></input>

This would do the trick if you do not want to trouble with js.

Upvotes: 2

rboling
rboling

Reputation: 727

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()" />
`

Upvotes: 16

hemanth
hemanth

Reputation: 1043

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();      
})

Upvotes: 3

njfife
njfife

Reputation: 3575

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

<input name="myTextInput" type="text" maxlength="5"></input>

Upvotes: 4

Related Questions