Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Alexander-Pop/fe060ceafd233632c77f21f4572503ce to your computer and use it in GitHub Desktop.
Save Alexander-Pop/fe060ceafd233632c77f21f4572503ce to your computer and use it in GitHub Desktop.
jQuery - Validate Min and Max Length of Input Field #jquery #form #validate
<input type="text" id="name"/>
<p id="warning></p>
var minLength = 18;
var maxLength = 24;
$(document).ready(function(){
$('#name').on('keydown keyup change', function(){
var char = $(this).val();
var charLength = $(this).val().length;
if(charLength < minLength){
$('#warning').text('Length is short, minimum '+minLength+' required.');
}else if(charLength > maxLength){
$('#warning').text('Length is not valid, maximum '+maxLength+' allowed.');
$(this).val(char.substring(0, maxLength));
}else{
$('#warning').text('');
}
});
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required having at most 4 characters.</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="field">Required, maximum length 4: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
field: {
required: true,
maxlength: 4
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment