Display custom errors with parsley.js 2.x

I need to show a list of validation errors in a popup. I disabled user interface modification using <form data-parsley-ui-enabled="false"... and subscribed to the "parsley: field: error" event, where I collect error information and then "parsley: form: validated " I show a popup, of course, only if isValid() == false . But I'm having problems getting the actual error message in the parsley: field: error handler. The handler receives a single parameter containing the object, which until now has been checked for several properties:

  • $ element is the actual jQuery field,
  • restrictions - list of restrictions
  • options.i18n - it has some source lines of error messages that I can obj.options.i18n.<LANGUAGE_CODE>.[obj.constraints[n].name] through the variable n as follows: obj.options.i18n.<LANGUAGE_CODE>.[obj.constraints[n].name] , but they, As a rule, they contain placeholders (% s) and therefore are not suitable for display until the end of the user; and sometimes there is an array instead of a single string that completely defeats the idea;

The question is, how do I get the actual error message that would be displayed if I hadn't disabled the user interface?

+2
source share
1 answer

Decision

Use the following method to access the error priority 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)); }); 

Brief explanation

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

Which is similar to the "data attribute to js variable conversion" convention, as in jQuery, it was mentioned in the docs: <parsleynamespace>-<constraint>-message becomes a <constraint>Message .

Having got this idea after viewing the annotated source for ui.js , check the _getErrorMessage function.


To access all validation messages for an error field (e.g. data-parsley-priority-enabled=false ), you can simply parsleyField.validationResult over the parsleyField.validationResult array:

 for (i=0; i<parsleyField.validationResult.length; i++) { console.log(parsleyField.options[parsleyField.validationResult[i].assert.name+'Message']); } 
+4
source

All Articles