简体   繁体   中英

How do I call a built-in parsley validator from javascript?

I'm using version parsley js, version 2.0.7. I would like to invoke a built-in parsley validator from a custom validator. For example I would like the attribute data-parsley-customtype="number" to behave exactly as data-parsley-type="numeric" .

Is there a way to invoke an already defined validator?

I finally analyzed a bit more the source code of the parsley validator and I found out that I can use something like this:

return window.ParsleyValidator.validate(value,
window.ParsleyValidator.validators.type("number"));

So you want to rename the built-in pasley validators? Why do you want to do that? (just curious)

You can define a new custom validator and redefine the same logic.

Try something like this:

window.Parsley.addValidator('customValidation', 
    function (value) {
        return true==(/^\d+$/.test(value)) // validates numbers 
    })
    .addMessage('en', 'customValidation', 'Your custom error message');

And don't forget to add the attribute to your element:

$("#element").attr('data-parsley-customValidation',$("#element").val());

Doesn't sound like a great idea (better use a standard when there is one), but you could call addConstraint yourself.

Eg (untested):

$('[data-parsley-customtype]').each(function() {
  $(this).parsley().addConstraint('type', 'integer');
}

This is my example for React. Parsley version: "parsleyjs": "^2.9.1"

import Parsley from 'parsleyjs/dist/parsley.min.js';

export const addCustomValidator = (validatorName, validator) => {
    if(Parsley.hasValidator(validatorName)){
        Parsley.updateValidator(validatorName, validator);
    }else{
        Parsley.addValidator(validatorName, validator);
    }
}

data-parsley-number

addCustomValidator('number', {
        validateNumber: value => {
            return value && typeof value === "number" ? true : false;
        },
        messages: {
            en: "This is a number",
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM