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

jquery validation for blank space
jquery validate form before submit
jquery trim
jquery validate on submit
jquery trim input value
jquery validate success
jquery validation normalizer
jquery validation rules

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 validated?

The following is a cut down but working example of a form which validates a email address:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
           type="text/javascript"></script>
    <script src="http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js" 
           type="text/javascript"></script>
    <script type="text/javascript">
        $().ready(function() {
          $("#commentForm").validate({
            rules: {
                email: {
                    required: true,
                    email: true
                }
            }
          });
        });
    </script>
</head>
<body>

  <form class="cmxform" id="commentForm" method="get" action="">
     <label for="cemail">E-Mail:</label><input id="cemail" name="email"
      class="required email" />
     <input class="submit" type="submit" value="Submit"/>
  </form>

</body>
</html>

The problem is that some users are getting confused because they accidently enter some whitespace in their email address, e.g. "test@test.com ". And the form won't submit and has a error message: "Please enter a valid email address.". Non-techy users don't know how to spot whitespace and may just quit the site rather than try to work out what they've done wrong.

Anyway, I was hoping I could chain "jQuery.trim(value)" before the validation so the whitespace is removed and the validation error never occurs?

I could use addMethod to build my own email validation function. But I'm sure there's a more elegant solution?

I did this with success.

Instead of:

Email: { required: true, email: true }

I did this:

Email: {
    required: {
        depends:function(){
            $(this).val($.trim($(this).val()));
            return true;
        }
    },
    email: true
}

Re: jquery.validate plugin, Hi is there any way to trim the filed value before using jquery validate plugin http:/​/docs.jquery.com/Plugins/Validation/Validator. Thank You. Hi is there any way to trim the filed value before using jquery validate plugin http://docs.jquery.com/Plugins/Validation/Validator. Thank You.

This code works for me. I haven't used it much so there may be bugs.

It wraps each method and trims the first element which is value.

(function ($) {

    $.each($.validator.methods, function (key, value) {
        $.validator.methods[key] = function () {           
            if(arguments.length > 0) {
                arguments[0] = $.trim(arguments[0]);
            }

            return value.apply(this, arguments);
        };
    });
} (jQuery));

if you're using select2 and validation at the same time, I recommend to put el.val($.trim(el.val())); inside an IF like this: if(el.prop('type') != 'select-multiple'){el.val($.trim(el.val()));}. That way, your jquery validation will behave as expected, and it will let you select multiple items.

normalizer, Transform the value of an element and the result for validation instead of the initial value. ¶Example: Makes "field" required and use a normalizer to trim its value before validating just for the demos, avoids form submit. In this tutorial we will create a simple jquery validation in registration form, that used input fields in real world form and also we create the dynamic date using php loop and after fill in up the form jQuery will validate the valid values after the value is valid it will passed to the php file.

Since I want this behavior on all my forms by default I decided to modify the jquery.validate.js file. I applied the following change to onfocusout method:

Original:

onfocusout: function (element, event) {
    if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
        this.element(element);
    }
}

To:

onfocusout: function (element, event) {
    if (element.tagName === "TEXTAREA" || (element.tagName === "INPUT" && element.type !== "password")) {
        element.value = $.trim(element.value);
    }
    if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
        this.element(element);
    }
}

I do want to allow spaces at the begging and end of password.

autoTrim could be added as a property to options.

Testing the trim method jquery.validate, jquery.validate plugin – how to trim values before form validation a easy way to automatically trim form elements before they are validated? Tag: jquery,jquery-validate In my form I have validation using jQuery Validate. After completing validation, success message should be shown using jQuery Notification plugin.

I like the approach by xuser (https://stackoverflow.com/a/10406573/80002), however, I do not like messing with the plugin source code.

So, I suggest doing this instead:

 function injectTrim(handler) {
  return function (element, event) {
    if (element.tagName === "TEXTAREA" || (element.tagName === "INPUT" 
                                       && element.type !== "password")) {
      element.value = $.trim(element.value);
    }
    return handler.call(this, element, event);
  };
 }


 $("form").validate({
    onfocusout: injectTrim($.validator.defaults.onfocusout)
 });

jquery.validate plugin how to trim values before form validation , <input type='submit' name='Submit' value='Submit' />. 17. </p>. 18. </form>. 19. ​. 20. <p>. 21. Steps to reproduce: 22. <ol>. 23. <li>Submit the form without entering anything</li>. 24. <li>Observe the validation complains for required fields</li> Testing the trim method suggested at http://stackoverflow.com/a/​6472021/  Validate the form on submit. Set to false to use only other events for validation. Example: Disables onsubmit validation, allowing the user to submit whatever he wants, while still validating on keyup/blur/click events (if not specified otherwise).

When downloading validator.js, there is a file called additional-methods.js that contains the method "nowhitespace" and "lettersonly" that will strip out any white space in a field.

rules: {
  user_name: {
    required: true,
    minlength: 3,
    nowhitespace: true
  }
}

jquery-validation, jquery.validate plugin how to trim values before form validation? function injectTrim(handler) { return function (element, event) { if (element.tagName  Doesn't change the elements' value, it only changes the value used for validation. Gets the value passed as argument, and "this" within it references the corresponding DOMElement. For versions between 1.15.0 and 1.17.0, it must return a string value. And as of 1.17.1, it can return any value including null and undefined.

Jquery validation code for not allowed only blank space in textbox, jQuery Validation Plugin - Form validation made easy Then select a form to validate and call the validate method. As of version 1.14.0 this plugin stops trimming white spaces from the value of the attached element. the normalizer that can be used to transform the value of an element before validation. As of version 1.14.0 this plugin stops trimming white spaces from the value of the attached element. If you want to achieve the same result, you can use the normalizer that can be used to transform the value of an element before validation. This feature was available since v1.15.0. In other words, you can do something like this:

1.5.5 --- * Fix for http://plugins.jquery.com/node/8659 * Fixed trailing , Client side validation for "No Space Allowed" in input field, You can use jquery.​validate plugin - how to trim values before , Anyway, I was hoping I could chain  This code loops through all of the inputs in the form and prevents form submission by returning false if any of them have no value. Note that it doesn't display any kind of message to the user about why the form failed to submit (I would strongly recommend adding one). Or, you could look at the jQuery validate plugin. It does this and a lot more.

jquery.validate plugin, 1.5.5 --- * Fix for http://plugins.jquery.com/node/8659 * Fixed trailing comma in to work with trimmed value (regression from 1.5 where general trimming before validation checkForm to validate a form without UI sideeffects * Rewrote custom  Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Comments
  • Great question. Jörn said he would fix this as part of the plugin itself. But that was about a year ago. I can confirm that white space at the end of a field does make it invalid for me. I'm using version 1.5.5. (Jorn's post: mail-archive.com/jquery-en@googlegroups.com/msg55651.html)
  • Reading this question and all the answers makes me feel as if HTML is just so damned broken.
  • The beauty of this approach is that the server side receives clean (trimmed) values too. But it would be quite an effort to add this if you have many validated forms with similar requirements. This is why I've combined this with @hwiechers' answer below :)
  • ... A warning could be useful where this is used: "Leading and trailing spaces are not valid and trimmed." Especially for users who want to use a password with leading/trailing spaces. They would be unable to log in since the recorded passwords would be different from the ones they'd intended.
  • A warning for an issue which I've detected after using this for quite some time: if the form is submitted while the the field is invalid, entering legitimate space (e.g. the ones between names and surnames) afterwards into it gets hard esp. for slower typers: jsfiddle.net/halilim/ftwqg Set onkeyup: false to prevent this.
  • @HalilÖzgür where do I have to put "onkeyup: false" to prevent that issue? Thank you!
  • @superpuccio for all of your validations: jQuery.validator.setDefaults({ onkeyup: false /* , other defaults */ }); for a single instance: <selector>.validate({ onkeyup: false, rules: { /* ... */ } });
  • Very useful since all methods in all forms can be modified once. To combine this with the above (accepted) answer, replace arguments[0] = $.trim(arguments[0]); with var el = $(arguments[1]); el.val($.trim(el.val())); (two lines).
  • A note after using this for quite a time: see my warning comment under the accepted answer, which is especially true when you apply trimming to all fields.
  • This was incredibly helpful in my validations today. Can't tell you how much this helped me, but I'm very glad it was there in the webz for me to see. Thanks!
  • I don't understand where should I be putting this code?