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

How to pass in transaction object in custom validation? #4714

Closed
rbudiharso opened this issue Oct 23, 2015 · 3 comments
Closed

How to pass in transaction object in custom validation? #4714

rbudiharso opened this issue Oct 23, 2015 · 3 comments

Comments

@rbudiharso
Copy link

@rbudiharso rbudiharso commented Oct 23, 2015

How to pass in transaction object to be use in custom validation/model validation? hooks can access it via options object

sequelize.define('Model', {
  username: {
    type: DataType.STRING,
    validate: {
      customValidation: function(value) {
        // how to get transaction object here?
        // someQuery
      }
    }
  }
}, {
hooks: {
  beforeCreate: function(instance, options, fn) {
    // here we got options.transaction <== like this
  }
});
@janmeier
Copy link
Member

@janmeier janmeier commented Oct 26, 2015

Hmm, I honestly don't think you should be able to access options in the validator for a single attribute. If you need to do any validations that are more involved I'd recommend before/afterValidate hooks

Loading

@rnemec
Copy link

@rnemec rnemec commented Jan 5, 2017

I don't think running an additional query in a validator is involved.

Loading

@guisehn
Copy link

@guisehn guisehn commented Nov 21, 2019

Although there's no way to access the transaction inside an attribute validator function, you can transform your validation into a model-wide validation -- which has access to the instance -- and then inject the transaction object into your instance during the beforeValidate hook.

I made a blog post describing how I did that and it worked: https://blog.guisehn.com/access-sequelize-transaction-model-validator/

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants