Question

I need to show a list of validation errors in a popup. I've disabled UI modification with <form data-parsley-ui-enabled="false"... and subscribed to the "parsley:field:error" event, where I collect error information, and then on "parsley:form:validated" I display the popup, ofcourse only on the condition isValid() == false. But I am having problems with getting the actual error message in the "parsley:field:error" handler. The handler gets a single parameter containing an object, which so far I inspected to have several properties:

  1. $element - the actual jQuery field,
  2. constraints - list of constraints
  3. options.i18n - it has some raw error message strings which I can get iterating with an n variable like so: obj.options.i18n.<LANGUAGE_CODE>.[obj.constraints[n].name], but they ocasionally contain placeholders (%s) and therefore are not suitable for display to the end user; and sometimes there's an array instead of a single string, which defeats the idea completely;

The question is, how do I get the actual error message which would got displayed if I hadn't disabled the UI?

Était-ce utile?

La solution

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']);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top