Question

I have the following field that uses it's own regular expression to validate:

<input type="text" name="first-name" class="form-control" id="first-name" placeholder="First Name" 
       data-parsley-trigger="change" required data-parsley-alpha data-parsley-pattern="^[A-Za-z]*$"/>

The field has multiple validation failure states, and I want each of those states to have a different error message.

For example, if the user enters a space, I want the error message to say "No spaces allowed", but if it has a numeric character, I want the error message to say "No numbers allowed".

I've tried to figure out how to do this by reading the docs, but I'm still confused on how to achieve this.

I'm using Parsley 2.0.0-rc4

Était-ce utile?

La solution

Yeah, this is not something easily doable with Parsley. Each validator have an unique error message.

If you want to do so, for UI/UX purposes, you may have two possibilities:

1) You'll need to define some custom validators of yours, and their related messages.

In your example:

  • create a validator nospaces and its message with 66 priority
  • create a validator nonumbers and its message with a 65 priority
  • still use your pattern validator (64 priority) and eventually change its message by something like 'only alphanum allowed'

Add then these 3 validators to your input, and depending on their respective priority they would be fired in the right order to display the right error message you want as described in your question.

Pros: easily reusable
Cons: some work is needed

2) Keep your pattern validator, and bind a custom function to the parsley:field:error event for this input, and do your check to display the right error message you want for this field, and not the default one

Pros: less work maybe, in a single function
Cons: not much reusable

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top