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 ?
"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}$/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With