Parsley custom validator is not working for javasc

2019-07-19 14:58发布

问题:

I have the simplest possible form with the simplest custom validator and it is not working, see http://jsfiddle.net/M55M4/ What is wrong?

<form id="myform">
    <input type="text" data-parsley-myvalidator="foo" data-parsley-required />
    <input type="submit" />
</form>
$('#myform').parsley({
    validators: {
        myvalidator: function () {
            return {
                validate: function (value, requirements) {
                    alert('myvalidator');
                    return false;
                },
                priority: 32
            }
        }
    },
    messages: {
        myvalidator: 'my validator failed'
    }
});

回答1:

If Parsley js version is not critical I recommend you to update it to the latest one - v.2.0.2. According to the new API, custom validator should be defined the following way (http://jsfiddle.net/M55M4/6/):

window.ParsleyValidator.addValidator('myvalidator', 
function (value, requirement) {
    alert('myvalidator');
    return false;
}, 32)
.addMessage('en', 'myvalidator', 'my validator failed');


回答2:

Accepted answer is deprecated now.

Accessing the method 'addValidator' through ParsleyValidator is deprecated. Simply call 'window.Parsley.addValidator

Example of custom validator: date format validation dd/mm/yyyy with momentJS:

<input type="text" required="" data-parsley-dateformat="date" />

window.Parsley.addValidator('dateformat', {
    validate: function(value, id) {
        var isValid = moment(value, "DD/MM/YYYY", true).isValid();
        return isValid;
    },
    messages: {
        en: 'Please provide date in format dd/mm/yyyy'
    }
}) 

This example for Parsley v 2.6.0 on plunker: http://plnkr.co/edit/hYDd19uPbJzKRVf9IMsH?p=preview



标签: parsley.js