parsley.js how to trigger an error on a field with a custom error message

18,176

Solution 1

Parsley has some built-in ways of adding custom error messages.

var specificField = $('input.specific-field').parsley();
# add the error
window.ParsleyUI.addError(specificField, "myCustomError", 'this is a custom error message');
# remove the error
window.ParsleyUI.removeError(specificField, "myCustomError");

More info here: http://parsleyjs.org/doc/index.html#psly-ui-for-javascript

EDIT: This method is now deprecated (thanks to @giraff).

Solution 2

This is how I got it working for Parsley 2.8:

field.parsley().removeError('customValidationId');
field.parsley().addError('customValidationId', {message: "myCustomError"});

http://parsleyjs.org/doc/index.html#psly-ui-for-javascript

Here is a turnkey-solution that I used for showing error from AJAX to fields identified by their id:

// Removing errors from previous AJAX call
if ($('.js_error').length) {
    $('.js_error').parsley().removeError('myError');
    $('.js_error').removeClass('.js_error');
}

// Showing errors from current AJAX call
for (var idField in ajaxErrors) {
    var msg = ajaxErrors[idField];
    var field = $('#field_' + idField);
    if (field.length) {
        field.addClass('js_error');
        field.parsley().removeError('myError');
        field.parsley().addError('myError', {message: msg});
    }
}

This solution will not prevent form-submit, though (because it only displays error messages in the UI, the form validation logic is not touched). That's why Parsley.js favors custom validators.

Solution 3

maybe this:

$('input.specific-field').parsley().UI.manageError({error: 'this is a custom error message'});

Solution 4

data-parsley-error-message="my message" 

worked for me see http://parsleyjs.org/doc/index.html#ui-for-javascript for more info.

Share:
18,176
riccardolardi
Author by

riccardolardi

⛵️ Design Engineer, Tinkerer and Hacker with strong background in Software Development and Web Technologies. Love building things using code or my bare hands or both. Also love skateboarding, music, nature, science and art.

Updated on June 23, 2022

Comments

  • riccardolardi
    riccardolardi almost 2 years

    It would be great if it was possible to do such thing as

    $('input.specific-field').parsley('error', 'this is a custom error message');
    

    ...but I guess that isn't possible?

    How could I achive such thing?