Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Format constraint runs on empty values #192

Open
itamargiv opened this issue Jan 6, 2017 · 4 comments
Open

Format constraint runs on empty values #192

itamargiv opened this issue Jan 6, 2017 · 4 comments

Comments

@itamargiv
Copy link

Description

In case I need to validate the format of a non required attribute someAttribue, running the validate on this attribute when it is empty '' or ' ' will still return the validation failure message.

Desired use case

To skip the Regex comparison when an attribute is empty. This seems to be the inverse of #99 and indeed, this behavior was introduced in 0.11.0

Is there a way to mitigate between those two opposing use cases? Is there a workaround here that I am missing?

In any case, will revert to version 0.10.0 for now :)

@itamargiv
Copy link
Author

itamargiv commented Jan 6, 2017

#182 Seems to be related as well

P.S. Will be happy to create a PR if you point me in the right direction. I didn't get to dig into the code just yet.

@jakee
Copy link

jakee commented Jan 23, 2017

@itamargiv I have solved this problem by wrapping my format constraints in a function that returns false if the value is an empty string. You can read more about constraints as function here.

function optionalConstraint (options) {
  return function(value) {
    if (validate.isEmpty(value)) return false; // don't validate empty values
    return options; // use the provided constraint options otherwise
  }
}

This function can then be used to wrap your constraints like this:

  url: {
    length: {
      maximum: DEFAULT_FIELD_MAX_LENGTH
    },
    format: optionalConstraint({
      pattern: validURL,
      message: 'must be a valid URL'
    })
  }

The solution is very lightweight so at least I'm using it gladly over downgrading versions.

@itamargiv
Copy link
Author

@jakee Thank you for the workaround, looks great. I'll try to implement and update you if it worked for my usecase. I agree, a lightweight workaround is always much better than rolling back.

@ansman
Copy link
Owner

ansman commented Mar 21, 2017

From now on empty strings, arrays etc are treated as values.

You can use attributes.myAttribute = validate.sanitizeFormValue(attributes.myAttribute) (it's not documented but it will probably be made public)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants