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 ?

3 Answers 3

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}$/
}
Sign up to request clarification or add additional context in comments.

3 Comments

But how should I put a check on the numbers length ie minimum one is required ?
What is exactly the minimun
@YvesKipondo Basically, the author wants to have numbers field at least one value, non-empty, rest conditions are for values.
0

Try required: true

validate: {
    validator: function(values) { 
       // Write validator for each value
    },
    message: "add a custom message"
},
required: [true, "numbers cannot be empty"]

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.