jquery textarea validation

2019-08-11 19:34发布

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

3条回答
Emotional °昔
2楼-- · 2019-08-11 19:40

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.');
            });
            });
        }); 
查看更多
狗以群分
3楼-- · 2019-08-11 19:45
if($.trim($('#myTextArea').val()) == '') {
    //error
}
查看更多
女痞
4楼-- · 2019-08-11 19:58

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
        }
    }
});
查看更多
登录 后发表回答