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
Could you not bind the trim to a blur event? Something like...
$("#cemail").blur(function(){ $(this).val(jQuery.trim($(this).val()); });
This is what works for me:
$(':input').change(function() {
$(this).val($(this).val().trim());
});
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
}
In jquery validation you will find the below code:
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
}
Change the value.length to $.trim(value).length
For reference, until I find a more elegant solution, I'm using addMethod as follows:
// Extend email validation method so that it ignores whitespace
jQuery.validator.addMethod("emailButAllowTrailingWhitespace", function(value, element) {
return (this.optional(element) || jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
}, "Please enter a valid email");
$().ready(function() {
$("#commentForm").validate({
rules: {
cemail: {
required: true,
emailButAllowTrailingWhitespace: true
}
}
});
});
Note: this doesn't actually strip the whitespace from the field, it only ignores it. So you need to ensure you perform trim
on the server-side before inserting in the DB.
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;
}
}
}
});