Reputation: 959
I have 3 phone fields and at least one of them must be filled. The problem is that parsley validation does not work when field is empty, so it does not show any error. How can I trigger validation even when field is empty?
Here is HTML:
<form parsley-validate id="demo-form">
Phone1 <input type="text" name="phone1" id="phone1" /><br>
Phone2 <input type="text" name="phone2" id="phone2" /><br>
Phone3 <input type="text" name="phone3" id="phone3" parsley-phones /><br>
<input type="button" value="submit" onclick="$('#demo-form').parsley('validate');">
</form>
And here is Javascript:
(function ($) {
window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
validators: {
phones: function () {
return {
validate: function(val) {
if($("#phone1").val()=='' && $("#phone2").val()=='' && $("#phone3").val()=='')
return false;
else
return true;
}
, priority: 100
}
}
}
, messages: {
phones: "At least one phone number is required."
}
});
}(window.jQuery || window.Zepto));
Upvotes: 1
Views: 6541
Reputation: 682
You probably just have to add a special attribute data-parsley-validate-if-empty
to the input.
Here is the relevant part of parsley.js source code:
// An empty optional field does not need validation
needsValidation: function needsValidation(value) {
if ('undefined' === typeof value) value = this.getValue();
// If a field is empty and not required, it is valid
// Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators
if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false;
return true;
},
And documentation: http://parsleyjs.org/doc/#psly-usage-field Quote:
A field is by default not validated if it is not required and empty. By adding data-parsley-validate-if-empty, validation will be done even if field is empty. Useful if you need some custom validators that check something particular when a field is empty.
Upvotes: 5
Reputation: 49
Just add the attribute, "required" to each input that you want to prevent from being submitted empty. For example:
<input type="text" name="phone1" id="phone1" required />
Upvotes: 1
Reputation: 1044
You should listen to the event before validation:
$.listen('parsley:field:validate', function(){
# your validation here
})
http://parsleyjs.org/doc/index.html#psly-events-usage
Upvotes: 0