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.

Unique email validation before create new record

See original GitHub issue

Am trying to validate Email already exists validation in Bookshelf.js when creating new record.

I found one solution here github but its not working, even i tried with Promise

User = bookshelf.Model.extend({
  tableName: 'users',
  initialize: function() {
    this.on('saving', this._assertEmailUnique);
  },
  _assertEmailUnique: function(model, attributes, options) {
    if (this.hasChanged('email')) {
      return this
        .query('where', 'email', this.get('email'))
        .fetch(_.pick(options, 'transacting'))
        .then(function (existing) {
          if (!existing) throw new Error('duplicate email');
        });
    }
  }
});

For Model validation currently am using Joi, looks like Joi also not supporting for custom validation for this. Am using Postgres Database. There is any other way to do it… Please help…

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
rhys-vdwcommented, Jul 6, 2016

Just put a unique constraint on the column…

On Wed, Jul 6, 2016, 8:51 PM raj-optisol notifications@github.com wrote:

Closed #1313 https://github.com/tgriesser/bookshelf/issues/1313.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/tgriesser/bookshelf/issues/1313#event-714168813, or mute the thread https://github.com/notifications/unsubscribe/AAyLWRUk6vWS6dE_Ma73suSk3WczZw8Lks5qS4ivgaJpZM4JDqK6 .

1reaction
aj0strowcommented, Oct 21, 2016

Here’s what I’m using. Start with a unique constraint.

// migration file

knex.table("table_name", t => {
  t.unique("unique_column_name")
  t.unique("compound_index", "part_two")
})

Then count duplicates on each create or save, respecting transactions, and filtering out the current model from the count.

function assertUnique(/* columns */) {
  const columns = _.toArray(arguments)
  if (columns.length === 0) {
    throw new Error("please pass unique columns")
  }
  return function(model, attributes, options) {
    const hasChanged = _.some(columns, column => {
      return model.hasChanged(column)
    })
    if (model.isNew() || hasChanged) {
      return this.constructor.query(q => {
        columns.forEach(column => {
          q.where(column, '=', model.get(column))
        })
        if (!model.isNew()) {
          q.where(model.idAttribute, '<>', model.id)
        }
      })
      .count({ transacting: options.transacting })
      .then(n => {
        if (n > 0) {
          return bluebird.reject({
            name: "DuplicateError",
            message: columns.join(", ")
          })
        }
      })
    }
  }
}

Then run the assertion for any model with unique constraints.

// users
  this.on("saving", assertUnique("email"))

// posts
  this.on("saving", assertUnique("md5_hash"))
  this.on("saving", assertUnique("user_id", "title"))

It should work for most use cases.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Bookshelf.js unique email validation before create new record
Am trying to validate Email already exists validation in Bookshelf.js when creating new record. I found one solution here github but its not ......
Read more >
Unique email validation - ServiceNow Community
I have a Record Producer to create a record on the sys_user table. I have an OnSubmit client script that checks the email...
Read more >
Unique Record Validation | Tadabase
In this short article we'll look into 3 different unique record validation approaches available to you. Assigning unique record validation on the field...
Read more >
Validation - IHP Guide
Validating An Email Is Unique​​ You can use |> validateIsUnique #email to validate that an email is unique for a given record. This...
Read more >
Validations & Constraints - Sequelize
The most basic example of constraint is an Unique Constraint. ... Validations are automatically run on create , update and save .
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