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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
if($.trim($('#myTextArea').val()) == '') {
//error
}
回答2:
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
}
}
});
回答3:
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.');
});
});
});