Date and Length Validators2:33 with Guil Hernandez
isDate validator to check for valid date strings for the birthday field, and use the
len (or length) validator to allow a password value only if it falls within a specific length (or an expected range) of characters.
DATEONLY data type follows the ISO international date format. It formats the date as:
You could set the value to '12-02-2000', for example, or even 'December 2, 2000', and Sequelize would still format it to ISO 8601 for the database. This ensures that all dates are stored in a consistent format.
- Per-attribute validations
- A thread regarding the Moment.js deprecation warning you may notice in the console when entering dates that are not in ISO format
- Use international date format (ISO)
Now I'm going to use the isDate validator to check for validate strings for 0:00 the birthday field and use the len or length validator to allow a password 0:06 value only if it falls within a specific length or an expected range of characters. 0:11 Earlier I used the notEmpty validator for 0:17 the birthday attribute to disallow empty strings. 0:20 You can use the isDate validator for that too, and to allow valid date strings only. 0:24 In the birthday object, I'll change notEmpty to isDate, and 0:29 change the custom error message to your birthday must be a valid date. 0:34 Next, let's allow only password values that are between 8 and 0:46 20 characters by adding the len property inside the password validate object. 0:51 When you set a validator to an object, you can pass values or 0:57 arguments to it via an args property. 1:01 For example, if I wanted the password to be at least eight characters long, 1:04 I can set args to 8. 1:08 In this case, I'll set it to an array specifying the range between 8 and 20. 1:09 And I'll once again use the msg property to set a custom error message. 1:17 The password should be between 8 and 20 characters in length. 1:21 Finally, I'll test the two new validators in Postman. 1:37 First, I'll try sending a post request by setting the birthday 1:40 field to jan and password to a short value like hello. 1:45 I'll make sure to set a unique email address too. 1:49 And this throws a sequelize validation error with the messages, 1:59 your birthday must be a valid date and the password should be between 8 and 2:03 20 characters and length. 2:08 Changing birthday to 2000-12-02 and 2:10 password to helloTreehouse works. 2:16 I get back a 201 created status response. 2:21 And if I make a get request to the API users routes, I see the new user, great. 2:24
You need to sign up for Treehouse in order to download course files.Sign up