Question

Any idea how I can add multiple regex pattern validators in parsley.js? My code looks something like this:

<input type="password" id="password" name="password" autocomplete="off"
data-parsley-pattern="^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$" 
data-parsley-pattern-message="error1"
data-parsley-pattern="\\s\\s" 
data-parsley-pattern-message="error2"
/>

When I run it, I only get the "error1" message for both cases.

Était-ce utile?

La solution

Sadly, this is not possible.

You can only register only once a specific validator in a field.

Either you work a bit more on your regexp to mix both requirements, either you create your own customs validators (with different names) that does each one its validation part.

Best

Autres conseils

Based on your REGEX pattern, it looks like you're trying to validate multiple zip/postal codes. That's not something you can do with REGEX, and you can't use multiple patterns with Parsley, but you can make a custom Parsley validation. Here's an example of one I wrote for validating both US (United States) Zip Code and Canada Postal Code. You don't need "custom validators with different names" like the accepted answer suggests.

JavaScript

window.Parsley.addValidator('validateZipcode', {
    validateString: function(value) {
        if (/^(\d{5}([\-]\d{4})?)$/.test(value)) { // United States Zip Code Format
            return true;
        } else if (/^([A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9])$/.test(value)) { // Canada Postal Code Format
            return true;
        } else {
            return false;
        }
    },
    messages: {
        en: 'US format:<br>00000 or 00000-0000<hr class="mt-1 mb-1">Canada format:<br>A0A A0A'
    }
});

HTML

<label class="hidden" for="zip-code">Zipcode</label>
<input
    required
    type="text"
    id="zip-code"
    placeholder="Zip Code"
    maxlength="10"
    data-parsley-trigger="change"
    data-parsley-required-message="Zipcode required"
    data-parsley-validate-zipcode=""
>

REGEX patterns pulled from: http://html5pattern.com/Postal_Codes

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top