Improved ‘equalto’ validation for Parsley.js

I’ve been playing with Parsely.js for form validation on a client project. It’s pretty nice, but I was unhappy with the ‘equalto’ implementation. ‘equalto’ allows you to link two fields whose entries should always match, such as when you have password or email confirmation fields during account registration. parsley-equalto is not symmetrical. If you enter some text into A, and enter non-matching text into B, B will not validate. If you correct B so that it matches A, then B will validate. So far, so good. But if you correct A so that it matches B, it won’t change the validation.

So I wrote a custom implementation that triggers validation on the paired field, making the link between the fields symmetrical. It’s pretty ugly (to avoid recursion) and doesn’t have any error handling, but it should point you in the right direction. (I’ve called it iff, which you can look up.)

The markup:

[code language=”html”]


[/code]

The validator:
[code language=”javascript”]
var iffRecursion = false;
window.Parsley.addValidator( ‘iff’, {
validateString: function( value, requirement, instance ) {
var $partner = $( requirement );
var isValid = $partner.val() == value;
if ( iffRecursion ) {
iffRecursion = false;
} else {
iffRecursion = true;
$partner.parsley().validate();
}
return isValid;
}
} );
[/code]

2 thoughts on “Improved ‘equalto’ validation for Parsley.js

  1. André Kelling

    oh got a similar approach. but was searching for when the confirmation field is not a mandatory field.
    a validation trigger here:
    have to give data-parsley-trigger-field with the id of the field you want to trigger.

    plugin.inputs.triggerFieldValidation = function() {
            var controls = '[data-parsley-trigger-field]';
            $('main').on(window.ParsleyConfig.trigger, controls, function () {
                var $this = $(this).data('parsley-trigger-field');
                var target = $($this);
                if (target.val().length > 0) {
                    // just trigger if target has something inserted
                    target.parsley().validate();
                }
            });
        };
    
    Reply
  2. Robb

    Sorry to bring this from the graveyard but this solved my issue! I could not get the new 2.8 stuff to properly validate passwords for some reason (I think I have a conflict with another library hijacking an event on password fields).

    Thanks!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *