jquery textarea validation
How to check for null,white spaces and new lines while validating for a textarea using jquery. If the textarea is empty and has 开发者_开发问答only new lines or spaces should raise an alert
if($.trim($('#myTextArea').val()) == '') {
//error
}
Assuming html that looks like
<form id='someForm'>
<input type="text" id='textInput' name='textInput'/>
</form>
First create a jquery validation method.
jQuery.validator.addMethod("checkForWhiteSpaceErrors", function(value, element, param){
var elem = $(element);
var val = element.val();
//Now you have a choice. Either use trim, or if you believe that
// that is not working, use a regex.
if(val && $.trim(val) == '') {
return false;
}
//or
if(val && val.match(/^\s+|\s+$/g)) {
return false;
}
return true;
}, "Newlines and White Spaces are not allowed.");
Now its a simple matter of telling the form validator to use this method.
$('#someForm').validate({
rules: {
textInput: {
checkForWhiteSpaceErrors: true
}
}
});
Thanks 'Keith Rousseau'! it worked. moreover if you have one text-box and one textarea than below jquery code will be fine:
$(document).ready(function () {
$('#message_submit').click(function (e) { //submit button ID
var isValid = true;
$('input[type="text"]').each(function () { //textbox type
if ($.trim($(this).val()) == '' || $.trim($('#body').val()) == '') { //#body is textarea ID
alert('Text box can't left empty');
return false;
}
else
alert('Thanks for your valuable input!\nWe will get back to you soon.');
});
});
});
精彩评论