John Cooling
John Cooling

Reputation: 415

Parsley - Error message being used over Required Message when field is empty

I have added a custom validator to parsley which is working as expected but the only problem I have is that the data-parsley-error-message is being used over the data-parsley-required-message when the field has been left empty.

How can this be prevented so that the error message is used when validation fails and the required message is shown when the field is blank.

Current Code:

<input class="form-control" id="FirstName" name="FirstName" maxlength="20" data-parsley-required-message="Your first name was missing." data-parsley-validate-non-ascii="" data-parsley-error-message="Invalid Character Entered" data-parsley-trigger="blur" required="" data-parsley-id="3137" type="text">

 window.ParsleyValidator.addValidator('validateNonAscii', function (value) {
        return Validate(value);
    });

Upvotes: 0

Views: 2396

Answers (2)

John Cooling
John Cooling

Reputation: 415

Using the suggestion from Marc-André Lafortune, I managed to find my own answer by implementing a custom Validation Error Message:

I updated my HTML input to the following:

<input type="text" class="form-control" id="FirstName" name="FirstName" maxlength="20" data-parsley-required-message="Your first name was missing." data-parsley-validate-non-ascii="" data-parsley-validate-non-ascii-message="Invalid Character Entered" data-parsley-trigger="blur" required="" data-parsley-id="5021">

Then using an event listener, I was able to add the error message from the input to Parsley; which now shows the validation error when a invalid character is entered and the required message when the field is blank.

$.listen('parsley:field:error', function (fieldInstance) {
    var validateNonAsciiMessage = fieldInstance.$element.data('parsley-validate-non-ascii-message');

    if (validateNonAsciiMessage !== undefined) {
        window.ParsleyValidator.addMessage('en', 'validateNonAscii', validateNonAsciiMessage);
    }
});

window.ParsleyValidator.addValidator('validateNonAscii', function (value) {
    return Validate(value);
});

Upvotes: 0

Marc-Andr&#233; Lafortune
Marc-Andr&#233; Lafortune

Reputation: 79552

data-parsley-error-message will always have priority. Use data-parsley-validate-non-ascii-message instead.

Upvotes: 1

Related Questions