Last active
October 26, 2021 09:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="text" id="name"/> | |
<p id="warning></p> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(''); | |
} | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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