pp fernandes
pp fernandes

Reputation: 231

How can i validate Date of Birth using Express-Validato?

I am creating a web application where i cant add multiple users in this application but i need all my users with a certain age, for that restrition i am trying to validate the dbo with express validator but express validator only let me validate strings. How can i validate dbo with express-validator?

let tdate = new Date(); req.checkBody('datadenasc',"Error: Invalid Date of Birth!").isBefore(tdate.getFullYear()-18).isAfter(tdate.getFullYear()-65);

HTML:

| Dbo:
      input#datadenasc.input(type='date', name='datadenasc', required='')

Upvotes: 1

Views: 3492

Answers (1)

pp fernandes
pp fernandes

Reputation: 231

What i did was

    `let d = new Date();
     let year = d.getFullYear();
     let month = d.getMonth();
     let day = d.getDate();
     let cA = new Date(year - 18, month, day).toDateString();
     let cB = new Date(year - 65, month, day).toDateString();`

req.checkBody('datadenasc','Error: Invalid Date of Birth!').isBefore(cA).isAfter(cB);

On the first line i get today's date. Then on the second, third and fourth line i get from today's date the year, month and the day. On the last line i create two dates one is for the minimum age (cA) and the other is for maximum age (cB).

Finaly i compare the date i receive from input with the cA and cB dates.

(Note: Express Validator only validates Strings so i had to convert both (cB) and (cA) to strings using toDateString() method).

Upvotes: 2

Related Questions