custom error display with parsley.js 2.x

Deadly 提交于 2019-12-06 05:48:23

Solution

Use the following way to access a prioritized error message (i.e data-parsley-priority-enabled=true):

$.listen('parsley:field:error', function(parsleyField) {
    // parsley field
    console.log(parsleyField);

    // which constraint has failed
    console.log(parsleyField.validationResult[0].assert.name);

    // the data-parsley-<constraint>-message
    console.log(parsleyField.options[parsleyField.validationResult[0].assert.name+'Message']);

    // the default constraint fail message
    console.log(window.ParsleyValidator.getErrorMessage(parsleyField.validationResult[0].assert));
});

Short Explanation

You were almost there, the messages are stored in the options object itself, and the format for the message is like this: <constraint>Message, for example: requiredMessage.

Which is similar to the "data attribute to js variable conversion" convention like in jQuery, this has been mentioned in the docs: <parsleynamespace>-<constraint>-message becomes <constraint>Message.

Got this idea after seeing the annotated source for ui.js, check the _getErrorMessage function.


To access all the validation messages for a field on error (i.e data-parsley-priority-enabled=false), you can simply iterate through the parsleyField.validationResult array:

for (i=0; i<parsleyField.validationResult.length; i++) {
    console.log(parsleyField.options[parsleyField.validationResult[i].assert.name+'Message']);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!