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
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>
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())
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.
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');