guillaumepotier/Parsley.js — pull request #802 by marcandre (2014-12-20 00:11:58+00:00)
Title: Fix field creation problems

TLDNR: This PR takes the approach that Parsley can’t and shouldn't filter fields at the constructor level and changes `init` to always return a `ParsleyForm` or `Parsley{Multiple}Field`, never a naked `Parsley`. It also adds error containers lazily (separate commit, could be split in a different PR).

Details:
In different circumstances, when calling `$.fn.parsley`, I get `Parsley` instances when I want `ParsleyField`.

I do not understand the idea behind return `Parsley` instances; it is definitely not useful for me, but maybe I'm missing something?

In any case, the current algorithm to decide to return a ParsleyField vs Parsley is deeply flawed. Ex:

$(‘form').parsey()
$(‘input’).parsley() # => Parsley, should be ParsleyField

This is because `Parsley#init` relies on incompletely formed options. Before a `ParsleyField` is created, the `OptionFactory` has no parent set, so won’t inherit the form’s `excluded`.

In any case, I believe that filtering at this stage is not the best approach.

For example, it seems natural to me to be able to add a constraint to a field even if it is currently in the excluded list, to account for the case where it might become included. E.g:

$(‘form').parsey()
$(‘input’).parsley().addConstraint(…)
$(‘.some-button’).click( function() { $(‘input’).show() } )

Currently, the way to achieve this is harder as it requires to subscribe to ‘parsley:form:init’ event and add the constraint at that point. This example is simple, but imagine more complex cases, where the visibility of an input depends on different code, loaded in an order that might change (and could suddenly break things if it hides the field before it’s bound).

In short, trying to decide if an element is a valid input or not in the constructor is tricky, brittle and
best changed.

There was code to avoid creating a UI for excluded elements. I don’t think the condition was ever false, as parsley:field:init was never emitted for excluded elements.

I kept the code there in the first commit so that excluded fields don’t create UI unless it’s needed. This paves the way to a lazy adding of the error container. This avoids a some DOM pollution, in particular for fields that have no constraints… This last part could be separated in a different PR.