# Validators in Node js

While working with the mongoose schema and models when the user sends the data to the backend before storing the data directly in our database we need to validate the data based on some parameters. These parameters could be whether the data satisifies what we want to store whether the data is legit and so on.....

The required is one such validator only in the mongoose schema. It determines that before storing the complete object the given key is required

Some other examples of validators are maxlength, minlength etc

One such validator is enum. Lets say we have difficulty as one of the keys in the schema. In that case if we mention enum=["easy","difficult"] this means that the difficulty will only accept the two given values in the array. If the user writes easy then the data is accepted however if the user writes medium then error occurs.


Custom validators:

We can create our own validators as well. The validator is just a function which returns either true or false.  This can be achieved by using a validate key. 

For example:

price:{
type:Number,
required:[true,"Yes we need a price"],
validate:function(val)
{
   if(val<100)
  {return true}
 
  else
  {return false}
}

Hence the validate contains a callback function and the function has access to the value that the user passes


