How to validate combinations of values with Parsley?

3.2k Views Asked by At

I'm trying to write a validator for phonenumbers for Parsley. The phone-number form widget consists of two fields:

<div>
  <select name="country">
    <option value="DE">Germany</option>
    <option value="FR">France</option>
  </select>
  <input type="tel" name="number" data-parsley-phonenumber>
</div>

The validation function that I use looks like this:

function validatePhoneNumber(country, number) {
  // return true if valid else false.
}

I'm aware of the Custom Validator example in the documentation, but it seems to only work if I hardcode a global selector for the country select field into the validator attribute data-parsley-phonenumber='["global-selector-here"]'

Is there a way to solve this without such a global selector? or more specific: is there a way to access the ParsleyField.$element inside the validator function? What's the recommended way of doing multi-field validations with parsley?

1

There are 1 best solutions below

2
On

I would do it the way you refered (with data-parsley-phonenumber="#country" and then access the value with the requirement parameter), like this:

<input type="tel" name="number" data-parsley-phonenumber="#country" />
<script>
    $('#myForm').parsley();

        window.ParsleyValidator
            .addValidator('phonenumber', function (value, requirement) {
                var select = $(requirement).parsley().$element;

                // call your function with the text of the selected option
                return validatePhoneNumber(select.find(":selected").text(), value);

            }, 32)
            .addMessage('en', 'phonenumber', 'En message');
</script>

If you don't want to do this, you can access the ParlseyField object inside your addValidator, like this:

<input type="tel" name="number" data-parsley-phonenumber />
<script>
    $('#myForm').parsley();

        window.ParsleyValidator
            .addValidator('phonenumber', function (value, requirement) {

                var select = $("select[name=country]").parsley().$element;

                // call your function with the text of the selected option
                return validatePhoneNumber(select.find(":selected").text(), value);

            }, 32)
            .addMessage('en', 'phonenumber', 'En message');
</script>

Note that you need to be sure to define the addValidator after you have $('#myForm').parsley();.