jquery.validate plugin - how to trim values before form validation

前端 未结 16 682
野趣味
野趣味 2020-12-04 16:12

I\'m using the excellent jquery.validation plugin by Jörn Zaefferer and I was wondering whether there\'s a easy way to automatically trim form elements before they are valid

16条回答
  •  旧巷少年郎
    2020-12-04 16:58

    For reference, until I find a more elegant solution, I'm using addMethod as follows:

    // Extend email validation method so that it ignores whitespace
    jQuery.validator.addMethod("emailButAllowTrailingWhitespace", function(value, element) {
        return (this.optional(element) || jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
    }, "Please enter a valid email");
    
    $().ready(function() {
        $("#commentForm").validate({
            rules: {
                cemail: {
                    required: true,
                    emailButAllowTrailingWhitespace: true
                }
            }
        });
    });
    

    Note: this doesn't actually strip the whitespace from the field, it only ignores it. So you need to ensure you perform trim on the server-side before inserting in the DB.

提交回复
热议问题