pTutorial

New way to learn Programming

JavaScript length validation Jquery

JavaScript : HTML Form validation- restricting the length

Sometimes situation arise when webmaster restrict user to put limited number of character like password must be 8 character or user name must be 4 character. For this type of validation you can write simple JavaScript function with the help of length.

JavaScript length validation example

<!DOCTYPE html>
<html>
<head>
<script src="http://freeonlinecompiler.ptutorial.com/js/
jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#kk').click(function () {
var z = $.trim($('#uk').val());
var k=z.length;
if(k==""){
$("#divData").text("Please Enter first");
}else if((k<=10)){
$("#divData").text(z);
$("#uk").css("border-color","green")
return false;
}else{
$("#divData").text("You cannot Enter more 10");
        $("#uk").css("border-color","red")
return false;
}
})
});
</script>
<style>
table{
border: 1px solid #080808;
margin: 5px;
padding: 10px;
}

</style>
</head>
<body>
<h4>Length must be less than or equal to 10 </h4>
<table id="tab">
<tr>
</tr>
<tr>
<td>Enter Name *</td>
<td> <input type="text" id="uk" name="kk1"></td>
</tr>
<tr>
<td> <input type="submit" id="kk" value="Check"></td>
</tr>
</table>

<div id="divData"></div>

</body>
</html>

Download

Explanation

To restrict the user to put the fixed number of character use length method with input and put the data into the if condition. You can use multiple condition in single conditional block see the next example.

See Also


QUOTES OF THE DAY

Everything flows, nothing stays still.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER