whatgoodisaroad/validity — Issue #6: Validate optional input. Validate only if a value is entered
Author: dimuthun
Created: 2012-02-10 06:42:47+00:00
State: open

I have a range validation as below and it triggers validation even if user does not enter any value.

$('input[data-name="AMOUNTDUE"]').range(0.01, 99999999.99);

My requirement is to validate only if a value is entered by the user.
I searched in the Validity documentation to find a way to mark an input field as optional and validate only if a value is entered.

Is there is a way in Validity to full-fill this requirement?

I came up with a way to resolve this by implementing optional() validator as below.

$.fn.extend({
optional: function() {
var $obj = this;
var $reduction = ($obj.reduction || $obj).filter($.validity.settings.elementSupport);
// Array to store only elements that pass the regimen.
var elements = [];
// For each in the reduction.
$reduction.each(
function() {
// If the element has a value, include it in the reduction.
var val = $(this).val();
if (val.length > 0) {
elements.push(this);
}
}
);
// Attach a (potentially) reduced set of only elements that passed.
$obj.reduction = $(elements);
// Return the full set with attached reduction.
return $obj;
}
});

Please let me know your comments on the above.