kristianmandrup / schema-to-yup

Schema to Yup validation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom error messages are not displaying for "minItems" and "maxItems" validation for array type

ankitWOW opened this issue · comments

const { buildYup, types } = require("schema-to-yup");

const schema = {
  type: "object",
  $schema: "http://json-schema.org/draft-07/schema",
  $id: "example-conditional-rules",
  title: "Example of conditional rules",
  properties: {
    test: {
      type: "array",
      minItems: 3,
      maxItems: 5,
      nullable: true,
    }
  },
  required: ["test"]
};

const values = {
  test: [10]
};
const errMessages = {
    field: {
      required: "Test field is a required",
      minItems: "Test field must have at least 3 items",
      maxItems: "Test field must have less than or equal to 5 items"
    }
  }
  
const config = {
    errMessages
};


const yupSchema = buildYup(schema, config);

const validate = (schema, values) => {
  try {
    schema.validateSync(values);
  } catch (error) {
    console.log(new Error(error).message);
  }
};
validate(yupSchema, values);

Comparing them to similar min/max for string

  minLength() {
    const { minLength } = this.constraints;
    const errMsg =
      this.validationErrorMessage("minLength") ||
      this.validationErrorMessage("min");
    const newBase = minLength && this.base.min(minLength, errMsg);
    this.base = newBase || this.base;
    return this;
  }

  // todo: use NumericConstraint or RangeConstraint
  maxLength() {
    const { maxLength } = this.constraints;
    const errMsg =
      this.validationErrorMessage("maxLength") ||
      this.validationErrorMessage("max");
    const newBase = maxLength && this.base.max(maxLength, errMsg);
    this.base = newBase || this.base;
    return this;
  }

Array

maxItems() {
    const { maxItems, max } = this.constraints;
    const $max = maxItems || max;
    if (!this.isNumberType($max)) {
      return this;
    }
    if (!this.isValidSize($max)) {
      return this.handleInvalidSize("maxItems", $max);
    }
    const newBase = $max && this.base.max($max);
    this.base = newBase || this.base;
    return this;
  }

  minItems() {
    const { minItems, min } = this.constraints;
    const $min = minItems || min;
    if (!this.isNumberType($min)) {
      return this;
    }
    if (!this.isValidSize($min)) {
      return this.handleInvalidSize("minItems", $min);
    }
    const newBase = $min && this.base.min($min);
    this.base = newBase || this.base;
    return this;
  }

Yup, indeed missing the errMsg part.

Please try the latest commit to master which should fix it

Please try the latest commit to master which should fix it

Thanks for fixing this issue.
May I know when these code changes will be released in NPM?

30 mins

30 mins

Wonderful!

1.12.0 published with the fix

Awesome.