kristianmandrup / schema-to-yup

Schema to Yup validation
Other
283 stars 50 forks source link

refValueFor error messages not being returned #126

Closed jamaybyrone closed 1 year ago

jamaybyrone commented 1 year ago

Hello All

Current refValueFor functionality does not use the configured error message coming from "refValueFor" in the error messages section.

A good example would be the test 'confirm-password.test.js'

Change config to be:

config = {
      logging: true,
      // for error messages...
      errMessages: {
        confirmPassword: {
          refValueFor: "confirm password field must have the same value as password",
          required: "this field is required"
        }
      }
    };

Add in two new tests:

it('is invalid if blank and displays required message', async () => {
    try {
      schema.validateSync({ username: "jimmy", "password": "xyz123", "confirmPassword": "" });
    } catch (e) {
      expect(e.errors[0]).toBe('this field is required');
    }
  })

  it('is invalid if if confirmPassword does not match password', async () => {
    try {
      schema.validateSync({ username: "jimmy", "password": "xyz123", "confirmPassword": "xyz1234" });
    } catch (e) {
      expect(e.errors[0]).toBe('confirm password field must have the same value as password');
// however confirmPassword must be one of the following values: Ref(password) is returned
    }
  })

I've fixed this locally by going:

'mixed.js'

replace:

refValueFor() {
    let propRefName = this.constraints.refValueFor;
    if (this.isNothing(propRefName)) return this;
    this.logInfo("refValueFor", { propRefName });
    return this.apply(
      "when",
      (propRefName,
      (refValueFor, field) =>
        refValueFor ? field.required().oneOf([yup.ref(propRefName)]) : field)
    );
  }

with:

refValueFor() {
    let propRefName = this.constraints.refValueFor;
    if (this.isNothing(propRefName)) return this;
    this.logInfo("refValueFor", { propRefName });
    return this.apply(
        "when",
        (propRefName,
            (refValueFor, field) => {
              const errorText = this.errMessages[this.key].refValueFor
              if (errorText) {
                return refValueFor ? field.required().oneOf([yup.ref(propRefName)], errorText) : field
              }
              return refValueFor ? field.required().oneOf([yup.ref(propRefName)]) : field
            })
    )
  }
kristianmandrup commented 1 year ago

You are very welcome to make a PR with this improvement

jamaybyrone commented 1 year ago

@kristianmandrup thank you for the quick response, I have opened one up via: https://github.com/kristianmandrup/schema-to-yup/pull/127

jamaybyrone commented 1 year ago

Resolved in 1.12.8