Reputation: 15
I'm using jQuery validate a form and I need to display a textarea with minlength 1 letter and maxlength 500 letters.
How can I change maxlength parameter to validate a textarea considering only the letters and not the spaces?
Thanks
Upvotes: 0
Views: 1067
Reputation: 232
If you are using jquery-validate
that you mention. Then please add another js
that is additional-methods.min.js
which have a extra capability to handle custom logic
HTML page
<html>
<head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery-validate.js"></script>
<script type="text/javascript" src="/js/additional-methods.min.js"></script>
</head>
<body>
<form id="formID" name="formID" method="post">
<textarea id="textareaID" name="textareaID" ></textarea>
<input id="submitBtn" type="submit">
</form>
<script>
$(document).ready(function(){
$("#formID").validate({
rules: {
textareaID:{
required:true,
checkLenght:true
}
},
messages: {
textareaID:{
required:'Please enter',
checkLenght:'msg..'
}
}
});
});
$.validator.addMethod("checkLenght", function(value, element){
var count = (value.match(/\d/g) || []).length;
if(count == 0 || count >500)
return false;
else
return true;
/*here is example regex you can write as per you requirement*/
});
</script>
</body>
</html>
For your further refrence : https://jqueryvalidation.org/jQuery.validator.addMethod/
Hope my explanation is works for you.
Upvotes: 0
Reputation: 74420
You need to create your own custom rule, see e.g:
$.validator.addMethod('customLength', function (value, elm, param) {
//Your Validation rule here
return elm.value.replace(/ /g,'').length <= 500; // return bool
});
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
customLength: true
}
},
messages: {
"name": {
required: "Please, enter a name",
customLength: 'Custom error message!'
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
Upvotes: 1
Reputation: 4225
$(document).on('keyup','textarea',function(){
var textarea = $(this).val().replace(/ /g,'');
var newLength = textarea.length;
//set to new max length (basically 500 + whitespaces' length)
$(this).attr('maxlength',500 +($(this).val().length - newLength) );
});
Upvotes: 0
Reputation: 1500
Try this:
$(document).on('keyup','textarea',function(){
if($(this).val() != ""){
var textarea = $(this).val().replace(/ /g,'');
var length = textarea.length;
if(length > 500){
alert('Limit reached');
}
}
});
Upvotes: 0