4

I want to define a document as

numbers : ["99995", "44444", "666664".....]

The numbers shouldn't start with 0 and length should be 5. Also there should be minimum 1 element

The mongoose schema that I defined in something of this type

numbers: {
  type: [String],
  length : 5,
  validator : (num) => {
      return /[1-9]{1}\d{4}.test(num);
    },
    message: props => `${props.value} is not a valid number!` 
  }    
}

But how should I put a check on the numbers length ie minimum one is required ?

Ankuj
  • 713
  • 3
  • 10
  • 27

3 Answers3

2

"when you create a custom validator you can do any thing in your function to validate your data. You must only return true when the vlidation is passed and false if it fails."

validator: (num) => {
    if(num.length == 5) {
         return /[1-9]{1}\d{4}/.test(num); // You forgot to add / at the end of the RegEx
    }
    return false;
}

or you can use the match to validate string with regex instead of creating you own function

numbers: {
     type: [String], match: /^[^0]\d{4}$/
}
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
0

Try required: true

validate: {
    validator: function(values) { 
       // Write validator for each value
    },
    message: "add a custom message"
},
required: [true, "numbers cannot be empty"]
Shivam Pandey
  • 3,756
  • 2
  • 19
  • 26
0

This should work for you:

numbers: [{
    type: String,
    length: 5,
    required: [true, 'Why no numbers?'],
    validate: {
      validator: function(num) {
        return /^[1-9]{1}\d{4}$/.test(num);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
  }]

It forces at least one element (via required) and makes sure that you can only save a string which starts with a number bigger than 0, has 4 more characters and is exactly 5 char of length (via the custom validate function which uses regEx to test.

Akrion
  • 18,117
  • 1
  • 34
  • 54