0

In my express + mongo application, I am using mongoose for database schema.

For the schema, I need a custom validator say "for checking whether length is x"

Below is my schema containing that custom validator

var schema = new Schema({ ..., contactNumber: { type: Number, validate: [ { validator: hasLength, message: "Contact number must be 10 digits", length: 10 } ] }, ... } 

And below is the custom validator function:

function hasLength(str, length) { let pattern = "^d{" + length + "}$"; let regex = new RegExp(pattern, 'g'); return regex.test(str); } 

In this validator function, I want to access the length parameter from the above schema.

I know this function code will not work properly. So I need help from someone that how can I access that length variable in my validator function.

Your help will be highly appreciated :)

0

1 Answer 1

1

Maybe like this:

var schema = new Schema({ ..., contactNumber: { type: Number, validate: [ { validator: hasLength(10), message: "Contact number must be 10 digits", } ] }, ... } const hasLength = length => str => { let pattern = "^d{" + length + "}$"; let regex = new RegExp(pattern, 'g'); return regex.test(str); } 
Sign up to request clarification or add additional context in comments.

7 Comments

you could (should?) just use the built-in validators for this, however.
mongoose doesn't have such a built-in validator and also i want to study how to create such a custom validator. I will try your code and let you know the result.
@SherinJose You’re incorrect, they have min and max for number schemas and have minLength and maxLength validators for string schemas.
min and max for numbers are not for counting digits, it is the maximum number and minimum number.
I have checked your code and it is working fine for me. thank you @Adam
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.