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:

<input
  name="password"
  id="password"
  data-parsley-trigger="blur"
  data-parsley-iff="#password-confirm"
  data-parsley-iff-message=""
/>

<input
  name="password-confirm"
  id="password-confirm"
  data-parsley-trigger="blur"
  data-parsley-iff="#password"
  data-parsley-iff-message="Passwords must match."
/>

The validator:

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;
    }
} );

One thought 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

Leave a Reply

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