Question

I'm using Parsley v2, and I want to put all my errors in a div at the end of my form, instead of inline.

I'm doing this by adding data-parsley-errors-container="#error-container" to the form, which works.

However, if I style this, it's constantly visible. I want to hide it depending on whether the form is valid or not.

I want to be able to add a has-errors class to the form tag whenever the valid status changes.

Parsley 2 has a pubsub and listener feature instead of using callbacks and options. I'm not even sure of where to begin.

I can do

$.listen('parsley:form:validated', function(e){
  e.$element.toggleClass('error', !e.validationResult);
});

which works, but it doesn't update as I type in the fields.

Listening for the parsley:field:validated event doesn't give me a way to see the form's validation status, as far as I can tell.

Était-ce utile?

La solution

You're right, 'parsley:form:validated' would be only fired on whole form validation, and listening to parsley:field:validated won't say much on whole form validation state.

It is not planned to implement this kind of behavior natively in Parsley, since Parsley does not store validation results and re-run each time all validators on all fields to be stateless. But you could achieve what you want this way (and if useful could be added in some examples section in the doc):

$('#form').parsley().subscribe('parsley:field:validated', function(fieldInstance){
  if ($('#form').parsley().isValid())
    $('#form').addClass('parsley-valid').removeClass('parsley-invalid');
  else
    $('#form').addClass('parsley-invalid').removeClass('parsley-valid');
});

Note: .subscribe() on a form would listen also all fields events. That way, every field validation could be listened for this form, and run a form.isValid() (that does not triggers events, to avoid infinite loops) to re-compute the global form state.

It's a choice because quite consuming but it should do the job (I did not tested the code above, could have typos)

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