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.

Validate doesn't work with conditional required fields

See original GitHub issue

Do you want to request a feature or report a bug? Bug.

What is the current behavior? Conditional required fields don’t throw when using Model.validate().

If the current behavior is a bug, please provide the steps to reproduce.

const mongoose = require('mongoose');
const assert = require('assert');

run().catch(console.error);

async function run () {
  const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: { type: Number, required () {return this.name === 'John';} }
  });

  const User = mongoose.model('User', userSchema);

  const err = await User.validate({ name: 'John' }).then(() => null, err => err);
  assert.ok(err);
}

What is the expected behavior? Expects method to throw a validaiton error path age is requried.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version. Node.js: 14.15.5 Mongoose: 5.12.13 MongoDB: 4.4.3

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
vkarpov15commented, Jun 15, 2021

@AbdelrahmanHafez I agree, let’s discuss in your PR #10360

1reaction
IslandRhythmscommented, Jun 14, 2021

Ok so the problem is the this object. As a result, when you call User.validate, you need to include the other two parameters in that call. Set the 2nd parameter to null and the third parameter the same as the first, so for expediency’s sake you could create a variable and save it as that. more here

const mongoose = require('mongoose');
const assert = require('assert');

run().catch(console.error);

async function run () {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    await mongoose.connection.dropDatabase();
  const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: { type: Number, required () {return this.name === 'John';} }
  });

  const User = mongoose.model('User', userSchema);
  const obj = {name: 'John'};

  const err = await User.validate(obj, null, obj).then(() => null, err => err);
  console.log('hi', err);
  assert.ok(err);
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Conditional Required Field Not Validating - WordPress.org
Conditional Required Field Not Validating unless Clicking Next, Then Previous, Then it Checks Conditional Required. ... Both forms work perfectly fine here. Maybe ......
Read more >
Conditional Required Fields validation is not working
If you can switch fromjQuery Validation Engine to jQuery-Validate, this would be the solution: $("#form").validate({ rules: { fieldY: ...
Read more >
Conditional Required Fields not Evaluating [#2859667] - Drupal
When creating a condition for a non-required field and changing it to required based on a set of conditions, the required field isn't ......
Read more >
lightning web components - Conditional Validation not working
This is what i tried, but unable to comeup with a workaround. @api isNotRequired === false @track tempList; validates(){ var inputCmp = this....
Read more >
Solved: Re: Advice for Conditionally Required Fields
Hi. I'm again hoping you guys out there can assist me with a problem I am having in validating data entered into an...
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