javascripttrimformvalidation-plugin

how to trim non required field before validating it in javascript


How to trim the businessname before validation for a non-required field in the below code. am using jquery-validation@1.17.0 version to validate the form. for required filed I can able to trim, But I don't have any idea how to trim a non-required field. Thanks in advance

form.validate({
                rules: {
                    firstName: {
                      required: {
                              depends:function(){
                                        jQuery(this).val(jQuery.trim(jQuery(this).val()));
                                return true;
                                }	
                            },
                     
                    },
                    businessName: {
                        onewordonly: ['1'],
                        maxlength: 15,
                        lettersonly: true
                    },
					      
                },
                messages: {
                    firstName: {
                        required: "Please enter your first name",
                    },
                    
                    businessName: {
                        onewordonly: "bla bla",
                        maxlength: "bla bla",
                        lettersonly: "bla bla"
                    },
                   
                },
                
            });


Solution

  • You can use depends to execute trim in other parameters like lettersonly which accepts boolean as value.

    businessName: {
      maxlength: 15,
      lettersonly: {
        depends: function() {
          $(this).val($.trim($(this).val()));
          return true;
        }
      }
    }