Parsley custom validator is not working for javascript installation

帅比萌擦擦* 提交于 2020-01-04 04:24:05

问题


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



来源:https://stackoverflow.com/questions/24246098/parsley-custom-validator-is-not-working-for-javascript-installation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!