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

前端 未结 16 580
野趣味
野趣味 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 17:10

    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>
    
    0 讨论(0)
  • 2020-12-04 17:13

    I've found that the majority of these are not quite what is needed.

    Using the following only fires on form change rather than on key down allowing you to still check on key stroke for the rest of the validation.

    It's not as tidy as including it within the plugin, but it's an acceptable compromise.

    $('body').on 'change', 'form input[type=text], form input[type=email]',  ->
        $(@).val $.trim($(@).val())
    
    0 讨论(0)
  • 2020-12-04 17:14

    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.

    0 讨论(0)
  • 2020-12-04 17:15

    Add a new jQuery validator method requiredNotBlank. Then apply that function to your elements rather than the default required function. This solution doesn't change the original validator source code, nor does it modify the default required function, nor does it modify the element's value directly.

    // jQuery Validator method for required not blank.
    $.validator.addMethod('requiredNotBlank', function(value, element) {
        return $.validator.methods.required.call(this, $.trim(value), element);
    }, $.validator.messages.required);
    
    // ...
    $('#requiredNotBlankField').rules('add', 'requiredNotBlank');
    
    0 讨论(0)
提交回复
热议问题