Mangrio
Mangrio

Reputation: 1020

Ignore multiple fields in unique validation rule in AdonisJs

I am trying to to update my user and applying Unique validator on email to prevent duplicates.

I need to ignore email uniqueness for provided user_id, and those records which are marked is_deleted to 1.

Only first statement works, if I place is_deleted,1 before id,${data.user_id} it works for deleted. but not for user_id.

get rules() {
const data = this.ctx.request.post()
console.log('current context: ', data.user_id)
return {
  // email: `required|email|unique:users,email,id,${data.user_id},is_deleted,1`,
  email: `required|email|unique:users,email,id,${data.user_id}|unique:users,email,is_deleted,1`,
  phone_number: 'required|max:10',
  status_id: 'required'
  }
}

However, only first statement for ignore works, second one is not working

Upvotes: 0

Views: 1051

Answers (1)

Luis Guilherme Almeida
Luis Guilherme Almeida

Reputation: 101

I would recommend extending the validation framework and add a custom rule (a good name would be unique_email). You will find it more productive and testable. The code would be similar to this:

const uniqueEmailFn = async (data, field, message, args, get) => {
  const email = get(data, 'email')
  const userId = get(data, 'user_id')
  if (!email) {
    /**
     * skip validation if value is not defined. `required` rule
     * should take care of it.
    */
    return
  }

  const [table, column] = args
  const row = await Database.table('users')
    .where('id', userId)
    .where('email', email)
    .where('is_deleted', false)
    .first()

  if (row) {
    throw 'The inputted e-mail is already taken'
  }
}

Generally speaking, it's preferable to use the default rules for simple and generic validations, and business-specific ones can be added by extending the framework.

Upvotes: 2

Related Questions