Search code examples
validationmongoosemongoose-populate

Restricting numbers in mongo schema


I have a "due" field in my mongoose model for bills. The field represents a day of the month, a number from 1-31.

How can I change this validation to prevent numbers higher than 31 being accepted?

due: {
    type: Number,
    required: true,
    validate: {
      validator: function (v) {
        return /^(3[01]|[12][0-9]|[1-9])/.test(v)
      },
      message: props => `$(props.value) is not a valid calendar day`
    }
  }

Solution

  • Your regex is not valid. If you type 33 it still will match on first 3 etc.

    try: /(1|2)([0-9])|(3)(0|1)|^([0-9]){1}$/.test(v)

    due: {
        type: Number,
        required: true,
        validate: {
          validator: function (v) {
            return /(1|2)([0-9])|(3)(0|1)|^([0-9]){1}$/.test(v)
          },
          message: props => `$(props.value) is not a valid calendar day`
        }
      }
    

    You can test the regEx here and also see the detailed explanation as well.