kristianmandrup / schema-to-yup

Schema to Yup validation
Other
283 stars 50 forks source link

Custom Email Format Error shows built-in Error instead #41

Closed ritchieanesco closed 4 years ago

ritchieanesco commented 5 years ago

Ran the following test and the assertion failed.

let valid;
let message = {
  title: "email",
  type: "object",
  properties: {
    email: {
      type: "string",
      format: "email"
    }
  }
};
let config = {
  errMessages: {
    email: {
      format: "Email format incorrect"
    }
  }
};

// Below test fails
// Expects "Email format incorrect" but returns "email must be a valid email"
it("yup inserts custom messages for email format", () => {
  try {
    const yupSchema = buildYup(message, config);
    valid = yupSchema.validateSync({ email: "as" });
  } catch (e) {
    valid = e.errors[0];
  }
  expect(valid).toBe(config.errMessages.email.format);
});
kristianmandrup commented 4 years ago

Thanks. I've added this test to string tests as email2.test.js. Let's fix this issue next.

kristianmandrup commented 4 years ago

Just fixed this issue in latest master. See email2.test.js

See improved docs on error-messages

Now works with this config:

  let config = {
    errMessages: {
      emailAdr: {
        // note: would also work with email as the key
        format: "emailAdr must be a valid email"
      },
      // generic fallback message for any email format validation
      // note: if not present uses yup default validation message
      $email: "Email format incorrect"
    }
  };

The main fix in mixed.js:

  valErrMessage(constraint) {
    const { constraints } = this;
    const errMsg = this.errMessageFor(constraint);
    return typeof errMsg === "function" ? errMsg(constraints) : errMsg;
  }

  errMessageFor(msgName) {
    const { errMessages, key } = this;
    const errMsg = errMessages[key];
    return errMsg ? errMsg[msgName] : errMessages[`$${msgName}`];
  }