Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multiple validators to a Schema field #718

Closed
diogogmt opened this Issue Feb 6, 2012 · 1 comment

Comments

Projects
None yet
2 participants
@diogogmt
Copy link
Contributor

diogogmt commented Feb 6, 2012

I'm not sure if there is already way to add more than one validator to a field.

I'm working on a project and I wanted to add multiple validators to a field, so for example:

Instead of having:
'username': [func, 'error msg']

I wanted something like:
'username': [func1, 'error msg'], [func2, 'error msg2']

I came up with this solution:

  User = new Schema({
    'username': {
      type: String,
      validate: [validator1, 'validator1 error'],
    },
    'email': { 
      type: String,
      validate: [
        {
          'func': validator1,
          'error': 'validator1 error'
        },
        {
          'func': validator2,
          'error': 'validator2 error'
        },
      ],
    },
  });

I made some changes to the validate method to accept an object of validators:
diogogmt@23426c8
I tested the changes and apparently is working

I wasn't sure how to name the properties of the validator object, so I just gave 'func' for the function to be called when validating and 'error' for the error message

@diogogmt

This comment has been minimized.

Copy link
Contributor Author

diogogmt commented Feb 6, 2012

Reading the documentation I saw that it's possible to add multiple validators calling explicity the validate function on the Schema

User.path('username').validate(function (v) {
  return false;
  }, 'my error type'); 
  User.path('username').validate(function (v) {
    return true;
  }, 'another error');

Shouldn't also be possible to add multiple validators when defining the schema?

@aheckmann aheckmann closed this in 350fa94 Feb 9, 2012

aheckmann added a commit to aheckmann/mongoose that referenced this issue Feb 23, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.