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.
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()" />
`
You need to use the maxlength attribute for input fields, something like this should do it:
<input name="myTextInput" type="text" maxlength="5"></input>
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();
})
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With