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

Viewed 59239

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?

16 Answers

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.

Starting from jQuery Validation plugin version 1.15 a normalizer function is supported. The normalizer can transform the value of an element before validation.

Note that the result of the normalizer is only used for validation. If you would like to update the value of the element you must do so explicitly.

$("#form").validate({
    rules: {
        email: {
            required: true,
            email: true,
            // Optionally disable validation on every key press
            onkeyup: false,
            normalizer: function(value) {
                // Update the value of the element
                this.value = $.trim(value);
                // Use the trimmed value for validation
                return this.value;
            }
        }
    }
});

Use normalizer, Please check below example

<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script>
  $("#myform").validate({
    rules: {
      field: {
        required: true,
        normalizer: function(value) {
          // Trim the value of the `field` element before
          // validating. this trims only the value passed
          // to the attached validators, not the value of
          // the element itself.
          return $.trim(value);
        }
      }
    }
  });
</script>
Related