question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Schema not allowing blank field when explicitly set as notRequired()

See original GitHub issue

Describe the bug Schema not allowing blank field when explicitly set as notRequired()

To Reproduce Use this code:

const validate = (getValidationSchema) => {
  return (values) => {
    const validationSchema = getValidationSchema(values)
    try {
      validationSchema.validateSync(values, {abortEarly: false})
      return {}
    } catch (error) {
      return getErrorsFromValidationError(error)
    }
  }
}

const validationSchema = function (values) {
  return Yup.object().shape({
    email: Yup.string()
      .email('Invalid email address')
      .when('password', {
        is: (password) => !password || password.length === 0,
        then: Yup.string().email().required(),
        otherwise: Yup.string()
      }),
    password: Yup.string()
      .min(8, `Password has to be at least 8 characters!`)
      .matches(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/, 'Password must contain: numbers, uppercase and lowercase letters\n')
      .notRequired()
      .when('email', {
        is: (email) => !email || email.length === 0,
        then: Yup.string().required(),
        otherwise: Yup.string()
      }),
    confirmPassword: Yup.string()
      .oneOf([values.password], 'Passwords must match'),
  }, [ [ 'email', 'password' ] ])
}

Expected behavior Schema not allowing blank field when explicitly set as notRequired(). Still throwing error about the password field, even though I don’t want to make the user fill in the password field. For example, the user wants to update ONLY their email, or ONLY their password, but not both.

Platform (please complete the following information):

  • Browser Chrome
  • Version 89.0.4389.90

Additional context error

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
jakobsandbergcommented, Mar 25, 2021

The validation is failing because an empty string does not pass the regex test in string.matches. You can achieve the desired behavior by passing in excludeEmptyString: true in the options object for string.matches which will skip the evaluation of the regex test.

https://github.com/jquense/yup#stringmatchesregex-regex-options--message-string-excludeemptystring-bool--schema

0reactions
ProductOfAmericacommented, Mar 31, 2021

Any ideas @jakobsandberg

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to have an “optional” field but if present required ... - GitHub
Meaning a field may be missing but if it is present it should not be None. from pydantic import BaseModel class Foo(BaseModel): count: ......
Read more >
JOI validation would not allow Date to be null or empty string
I am doing a conditional check at the very top and if there is undefined being passed from the frontend, I am explicitly...
Read more >
Using Optional and Nullable Properties in API Requests
A null value is not allowed to be specified as required so it cannot be ignored. The rider_id is a non-nullable attribute in...
Read more >
17.7.0 API Reference - joi.dev
To disallow this behavior, you can either set the schema as required() , or set presence to "required" when passing options :.
Read more >
Working with nullable reference types - EF Core
An empty collection means that no related entities exist, but the list itself should never be null. DbContext and DbSet. The common practice...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found