Getting errors when extending validator via hooks.js

I followed the instructions on extending Validator via hooks.js: https://adonisjs.com/docs/4.1/validator#_extending_validator. However, I’m getting error stating that the rule does not exist.

Environment: "adonis-version": "4.1.0"

Error gotten: membershipIDExists is not defined as a validation rule

Route Validator code:

"use strict";

class StoreUserProfile {
  get validateAll() {
    return true;
  }

  get data() {
    let data = this.ctx.request.only([
      "profile_details"
    ]);

    const { auth_org_id } = this.ctx.request; // `auth_org_id` set from middleware
    const { org_id_set_by_superadmin } = this.ctx.request.post();
    const org_id = auth_org_id || org_id_set_by_superadmin;
    data = Object.assign({}, data, org_id);
    //console.log(data);
    return data;
  }

  get rules() {
    const { org_id } = this.data;
    try {
      return {
        "profile_details.membership_id": "required",
        "profile_details.membership_id": `membership_id_exists: user_profiles,membership_id,${org_id}`

      };
    } catch (error) {
      console.log(error);
    }
  }

  get messages() {
    try {
      return {
        "profile_details.membership_id.required":
          "You must provide a Membership ID.",
        "profile_details.membership_id.membership_id_exists":
          "This Membership ID has been used by your organisation.",
      };
    } catch (error) {
      console.log(error);
    }
  }

  get sanitizationRules() {
    try {
      return {
        "profile_details.membership_id": "strip_tags"
      };
    } catch (error) {
      console.log(error);
    }
  }

  async fails(errorMessages) {
    return this.ctx.response.status(400).send({
      message: errorMessages,
      status: 400,
      code: "INVALID_REQ_EXCEPTION",
      statusText: "Field validations failed."
    });
  }
}

module.exports = StoreUserProfile;

hooks.js

"use strict";

const { hooks } = require("@adonisjs/ignitor");

hooks.after.providersBooted(() => {
  const Validator = use("Validator");
  const Database = use("Database");

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

    const [table, column, org_id] = args;
    const row = null;

    try {
      row = await Database.table(table)
        .where(column, value)
        .where("users.organisation_id", org_id)
        .leftJoin("users", `${table}.user_id`, "users.id");
    } catch (error) {
      console.log(error);
    }

    if (!row) {
      throw message;
    }
  };

  Validator.extend("membership_id_exists", membershipIDExists);
});

Thank you for your help on this.

1 Like

Can you give longer stack trace where this error is coming from?