whatgoodisaroad / validity

Client-Side Validation for jQuery
http://whatgoodisaroad.github.io/validity/
132 stars 74 forks source link

optional field with validation dilemma #50

Closed cmanley closed 10 years ago

cmanley commented 10 years ago

Sometimes I have forms with fields that are optional, but if data is entered into them, then they must be validated against that data. E.g.: $('#company') .minLength(2) .nonHtml();

Currently the above validation causes an error message hint to be displayed when no data is entered into the field. Is there a solution for this? Thanks

Edit: it's the minLength() check triggering the 'problem'. I think require() should be the only method causing a field to be required, but if you think otherwise then perhaps it's an idea to add a minLengthOrEmpty() method, etc.

whatgoodisaroad commented 10 years ago

I see what you mean. When I designed minLength, I did envision it as a kind of substitute for require. However, your use-case here makes sense, so I think the behavior is wrong.

I'll go ahead and change Validity, but it's a behavioral change so I'll be making tests and it could take a few days before I commit it.

In the mean time, you can get the behavior that you want with an assert validator.

$("#company")
  .assert(
    function() { return $("#company").val().length != 1; },
    "Input must have at least 2 characters or nothing at all"
  )
  .nonHtml();

Hopefully this helps. Look for an update to Validity soon (like next few days).

whatgoodisaroad commented 10 years ago

I guess I over-estimated the effort on that. I've added a fix as of this commit.

Please let me know if this fixes the issue.

Thanks!

cmanley commented 10 years ago

It works nicely. Thanks!