Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Client and server-side validation
Lecture: Server-side validation with Viewmodels
0:00 The second core service that view models provide
0:02 to our application is server side validation.
0:05 So we've set all of these fields here in our initialization.
0:08 This is the data exchange
0:10 but sometimes, not all the time, sometimes
0:13 we need to validate it.
0:14 If we're just getting, doing a standard get
0:16 and showing the data, there's rarely a validation
0:19 but if we're working with forms in the post side of things
0:22 then we do want to validate that.
0:24 We could do that in the view method
0:26 but it's going to get all messy and why would we do it there?
0:29 We're going to move it down to a validate method.
0:30 So here, we're going to say if the first name is not set
0:33 or the last name is not set
0:35 we'll give an error, like hey you have to specify a name
0:37 or an email is not right, you got to specify an email.
0:40 Same for the password.
0:41 We saw lots of interesting validation that we could do here.
0:44 You can imagine we could make this nicer, right?
0:46 Regular expressions on emails and so on.
0:49 We also could see that we did richer types of validation
0:52 not just here's a required field, but we go to the database
0:56 and we say, someone's trying to register with this email
0:59 to somebody already exists
1:00 who has registered with that email.
1:01 Remember there's a uniqueness constraint
1:03 and it's going to actually be some kind of error
1:05 if we try to save it theoretically
1:07 and we want to give them a friendly message
1:08 instead of a crash that says hey that didn't work
1:10 for whatever reason.
1:12 So we can tell them really nicely
1:13 hey that user with that email already exists.
1:15 And even suggest, would you like to try to log in
1:18 or reset your password?
1:19 If you're trying to register, maybe you forgot
1:20 what your account is. Things like that.
1:22 So there's validation, it's really, really nice.
1:25 What's cool about it is, we can add tons of validation here
1:28 and it doesn't make our view method any more complicated.
1:32 This validate method just bundles it all up
1:34 and it's great, right here.