Hey guys welcome to another exciting video in our journey with a speed that MVC web development.
Today we will be looking into adding validations to our farms.
Now validations are very important because when we are accepting input from a user trying to storage
in our database we want to ensure that whatever we're passing with the database meets certain rules
at the very least a rule can be like you expect a text value for text field or the expected number value
for a number of fields or your text value should be at a certain length.
Those kinds of things those are validations that you want to ensure we do from the client side meaning
we don't want to try and hit the database with invalid data before we know if this data is admissible
or not.
So we want to add certain rules to our forms such that before the user is able to actually submit this
information we can ensure that everything matches a certain standard to kick things off we'll take a
look at our freight action in our course controller.
As you can see I'm already in debug mode but we want to take a look at what happens when we submit data.
So we have our create action which renders our form for free courses.
I'm just going to bring that up quickly.
We click on courses and then we click Create New which then renders our free view and then we ask the
user what is the title of this horse and how many credits should it be.
This is a number and I shouldn't be able to put in text those kinds of things matter when you want to
validate the information coming back.
If you take a look at what happens upon the post you see that it checks if model state is valid which
means it is assessing all of the information that's it just got from the user and see is this information
valid.
What we're going to do in this video is set up our own set of validations so that this automatically
assesses our rules and makes a decision based on that.
But before we do that we're going to take a look at the database and we're going to take a look at what
happens when we try to submit information.
If we take a look at the course table which I already have over here and look at the designer to see
that both title and credit columns are designed to low no values which in fairness is probably not the
best thing to do because then it allows me to create a course with no title and no credits which doesn't
really make sense.
It hits my breakpoint on this continuum and it goes ahead and it actually creates that empty record
with no value for a title and no value for credits and there is nothing there which is something that
we really do not want a user to be able to do.
So the first step would be to change the validation rules or change the data type rules on our database
so we can head back over to visual studio bringing up our designer for our course database and we say
we want to not alone knows.
So we take those alone those and then we can pick up eight then we say OK it's obvious this is going
to give us an error as you see on here because then we're sitting on our database to not accept those.
Well we have no values that exist.
So I distance to remove that no record.
And since I have my code operation I just do it here since my code works.
So I delete this record and I want to delete it.
And once again we hit a very point.
I'm just going to continue and there it is removed.
So now we can retry our save.
So I keep a bit of data again and then it is successful this time no less a strand had a course with
no title and no credits once again.
So we are going to leave these blank because we want to test if changing the know setting and the rules
that govern our data types in our database will be effective enough in setting up validations here.
So when we click creates we see that it actually hits an error it hits an exception saying that something
happened while trying to execute this.
And if you scroll down and read the details it says as a we cannot insert a no value into column type.
So we see that some amount of validation is actually occurring here.
But this is probably not the best because you don't want your application to actually pause like this
when a user is using it or give these kinds of errors that a user may not necessarily understand.
So effective continue then you see that the page precedes the load and very nasty looking error that
the typical user may not necessarily know how to process and may not want to see at all.
So we're going to have to modify this behavior a bit.
So I'm going to quickly exit debug mode and then we will get to work
know in order to actually add these validation rules.
We have to use some C sharp classes and not some o p type implementations to have a very fluid and somewhat
disjointed but unified solution and that sounds like a paradox.
But as I go through it you appreciate what I'm saying.
So the first thing we want to do is to take a look at our model.
So we said that we want to start adding validations to our courses.
So we draw a line into our models folder into our EDL mix diagram and then we drill down into our model
T T and look at our course class we need to appreciate what is here and do recall that each field that
is outlined here is synonymous with what is in the database.
So the fact that we see here that credit is to a notable value.
He's a we of Visit our database but we did not update our models.
So that is the first step we need to take.
So we vote for the mix diagram and then we right click in open space and click update from database
he will to refresh tray tables and take finish.
This then reloads our tables and since the last time we were here I added middle name and date of birth
to our student club.
Now do remember that each time we refresh or do meet a change of any sort to our diagram we need to
build so you can either go to build and click the solution or hold down control shift and B and that
will actually effect a build operation.
So I'm going to do that control shift and the mind is already built.
So when we go to our course that cease fire we will see that it is updated to show that it is no longer
a noticeable value a test to have an INT.
And the tests have a string and the test of an integer here.
So you can see that this change has been made successfully.
So that's a step one for validation making sure that our database reflects our ambitions.
Step two to our validation is to create what we call meta data.
Classes are already feeling the needs and means that we have to you call meta data which is pretty much
data about data.
So in this case we have data in the form of our model or our class or our database tables and the data
about that would be descriptions that we want.
And in this case the descriptions we want would be our validation rules.
OK.
So what we want to do at this juncture is to create some classes that would describe rules that will
govern our values here.
Now since the work we're able to do concerns models and the best place to go ahead and create the fires
that we need would be in the models folder.
But then if you look in the models folder you see that you already have a kind of variety at least if
you created the project in the way that I did with the individual user codes set up at the start then
you would have these view models already existing.
So in order to not mix and maintain that separation of concerns I'm just going to create a new folder
and I'm going to call it meta classes
and then inside amateur classes then I will have those meta data classes that I alluded to just not
the first one I create of course is one for courses so right click click Add create a class and I will
call this one courses meta data God and then that will give me this empty class.
No.
My first objective is to meet this empty class Miro.
My actual models so I can go back to my course that see us fail and find all of these properties that
are there for me.
I don't have to bring over I don't have to validate its course I did.
Because upon creation or ADR any operation we don't need to validate what the value is here.
What we may want to restrict any course title to a length of 50.
And we would want people putting in 50 credits for any course that they're creating maybe the maximum
number of critics that any course can BES 8.
So we're just going to copy these two over to them in our meta data class
and then proceed to add or validations before we move on.
In order to add our validations or what we call data annotations we have to include our library that
gives us that function.
So we'll see using system lots components model dots data notations.
Now you may not remember this but then when you see the pattern that I am able to use visual studio
will actually recognize this pattern and see to you that hey this is illegal.
You have to include this library to use this and then they would proceed to suggest that you include
that library.
So like I said the first thing I want to do is include a string length of 50.
So literally I'm going to say string length and there and so the sense finishes it for us.
And I'm going to see 50 0 if I remove this and notice that it has no come to life.
Everybody else is sort of somewhat green notes but this one is actually bold white text.
If I removed this then typing this would cause an error in Visual Studio and then they would suggest
to me that I need that library so you can always start typing it before and then include the library
retroactively.
Or you can just include this library and then you have no problem moving forward.
I also said that for my integer I want to restrict the range of values to me from one.
So that means you can't of course with zero credits and it should never pass hate
no.
It is.
Where are the off nodes that you can actually include these directly on your course.
That's you.
So you didn't have to necessarily go and create a whole new file a whole new folder and the whole new
file and then start from scratch and look those there you could actually put them right here above title
and both credits the downsides of this however is that each time the model gets generated or regenerated
or dated or change and you build your project then you're actually going to have this cease fire as
well with as every other one listed here refreshed.
So any changes that you made to it will be discarded.
So you really don't want to do that because that would lead to a lot of rework and you have to do this
each time.
So I am suggesting that you create this new file and then you associate it with that model using a partial
class and that we you have that.
As I said disjointed because they're actually different files but unified because they're making reference
to each other so it doesn't matter what happens here.
Even if the courses table ceases to exist these courses and metadata of course this table will not in
any way encroach on the operation of your system.
So next we're going to create actually another class and in C sharp you can actually use one cease fire
as a whole as many classes.
Some people say it's bad practice some people practice it it's up to you you can decide what you want
to do.
I'm just going to use this one C.S. Das called meta courses method data and I'm just going to create
another public class but this one will be partial public partial class and I'm going to give it the
same name as the model that I wanted to be associated with.
So that's one of those great bull P tricks where I can create.
Sorry the name of the class is course I can create a partial class and give it some properties and it
will work in conjunction with our original class.
What I wanted to do however is be associated with the meta data class so I'll use another data notation
and I see a meta data type and this is some fun C C sharp that's going to happen here but you can study
this pattern or just know how to do it when the time is right.
So I want to associate it with courses meta data so at the end of this exercise you would have created
a meta data class which would have data notations that will govern the validations of your fields and
you would have associated with the class coming from your model just in a very indirect and or P like
we know.
One final change before we move on and this is very very very important and it's a common mistake that
people would run into trying to maintain that separation of concerns but the partial class that you
defined needs to be in the same namespace as the class it is.
Well let's say pirates off.
So if I go to courses and I look at the namespace I see that it is in school and management but models.
If we look at where the namespace is for the partial classes see that is in modules thought classes.
So each folder determines that namespace hierarchy.
Right.
So we're going from the project school management tool folder called models so school management to
a folder called models of a folder called Method classes and that is its namespace.
So what we want to do is remove the metal thousands from the namespace.
We can leave it physically in the folder but the namespace associated with this folder and any other
file in that folder.
So by doing so we are putting or partial class on priority.
The hierarchical sense with its original counterparts so we can go ahead and actually debug and see
if our validation works hard again.
So we will look at the courses section and just run some tests to see if our validations are working.
So we go to create new and then firstly we're going to just click Create so they expectation is that
once invalid data is being sent across it will re both our attempts to create the record and this be
an error message.
So we create and without filling anything in.
We see that the pages of three loads with an error message the credits field is required.
We can quickly review where that error message is coming from.
I'm bringing up visual studio still in debug mode and I am just going to go over to our view for create
and courses and then we can just take a look at what is happening in the credits section of the form.
So remember we have that label which gives us the word credits and then we have the edit which gives
us our textbooks but then read underneath that we actually have an issue him a helper that is sending
back a validation message right.
And we see that the bootstrap class takes that danger is being applied.
So that is basically seeing that once I try to submit and I'm just going to go to my controller real
quickly and put a breakpoint right at this decision.
So he creates and it hits that breakpoint and then it evaluates if the model's state is valid and you
see that this is evaluating the Falls unlike all the other times in the previous examples where it validated
and which is true.
So if this validates the true then that should happen the fact that it goes to falls means that it will
just return the same view which is our create view and it will return whatever data was being submitted.
We know that we didn't try to submit anything.
So everything comes back as null and zero and then that is what triggers the display of or validation
message.
So if I put in a title and you can see that I was testing this thing.
So I put in a title with clearly more than 50 ages and do recall that our validation rule for courses
C is that we should only accept 50 or up to 50.
So if I take create it hits it again and it says that this state is not valid so it returns a view with
the data we see we get back our data alongside a displayed error message that we are exceeding or maximum.
And if I see a 10 critic course once again recall that or validation rule said one 2 eight.
So that means anything less than one and anything more than eight will trigger an error message.
So if I create once again it's our breakpoints the model validity is false.
So we continue and it will display an appropriate error message displaying to the user hey your data
is wrong for this reason.
And so this is a pretty cool feature that we can use to ensure that our users are staying within the
confines of what we expect for our data.
So I can create a legitimate course is the Mets and D.C. by Asian and that could be one credit course
and then I create.
And then we see it hits our breakpoints and this time everything is valid and because it is valid it
will go ahead and edit and see the changes and then redirect to our listing of courses.
So I press on to the expectation is fulfilled.
There we have our brand new course.
So that's it so you can go about setting validations on your fields no data annotations actually serve
a greater purpose than just setting validation rules they can actually influence what is displayed for
a farm or for a value in that display name for helper function.
So I understand to jump over to your studio real quickly and show you what I mean.
Do recall that we have the label for and then in our e Thales view we do have display name for.
So you can actually use data annotation to influence these.
The simple way to change this would be to erase it and rewrite what you once the downsides of that is
if the field changes or something abodes the what should be displayed changes and you have it sets at
different points off your project then you're going to have to manually go through and change it as
all those points which can be tedious if you however continue to use the HMO function and then you use
your data annotation then once you meet the change in the data annotation it will be made right across
your application.
So just as a quick example for or courses form we have title and credits just like the fields are in
our database.
All right title and credits.
So as they appear in our database that's how they get created in our module title credits and that is
what will be displayed in our label for on our page title and credits those details.
This year title and credits.
No it seems in a sense and it seems unimportant for our courses because we only have one word.
Well what about the case of students where we are actually collecting first name last name enrollment
age and other things so you can see here that the last name is appearing as it does in the database
with no space no discernible space here for human readability.
If we keep details we see everything above the students.
And once again this is not very human readable or friendly.
Now when we go to students online courses we don't have only one word but we have two words.
So we click on students and we see that we have the last name first name and enrollment date with no
discernible space in between these names and labels.
And that is not very user friendly.
That's not good.
We want to make sure that our users look at our screen and feel comfortable absorbing and digesting
our information.
And if I go to details Izzy it is a very similar situation.
So we're going to have to use some data annotation to clean this up and make our students much more
user friendly to when we're reading the information.
So back in Visual Studio we want to do is create two classes to associates with students.
One for our metadata and the one for all where parts of us and to recall that I created this older here
method classes or it's a visa but we subsequently need to change the name space so that everything flows
smoothly.
Someone's rightly had lots of class and we're creating students into data and then the easy way to go
about doing this is just to copy all of the fields that are coming back from our original module in
our database so we drill down into the EDL mix file we find students that see us and then we can copy
across all of these know notes once again that these things are no levels.
So for your own purpose you may go ahead and change a database of data your model.
But I really just need to give the data annotations here for student meta data so I copy those across
and we want to run some custom labels for all of these needs of these fields.
The first one I'm going to do is last name and I'm going to see string length and I'm just going to
set up a validation I don't want anybody entering a string length of more than 50 for our last name.
So I'm setting up a validation right here and you see the arrows being displayed and Visual Studio is
telling me I need to include this library in orbit.
So I use this function.
Secondly I want to see that the display
needs to have a name and I'm going to set a custom string and you can always pay attention to the tool
tips they're always guiding you as to what values can go in.
We want a name which is what is going to be displayed in the UI.
You can just read that description and ascertain what it is and I want to display in the UI a last space
name all right.
So we're moving away from last name as one perceivable word to two words and I can just reuse these
annotations for the first name.
I don't want more than 50 and first name just puts in space to make it look more beautiful enrollment
date.
Well I don't need to specify a length because this is a date.
The data type is already set.
It's an a low doesn't know anyway.
And I want to display enrollments date with a space or better yet it seems the top of it date of Rome
and so rewarding it just to show you that it's not a matter of or just putting a space in there you
can labile to whatever you want on your form.
All right.
And let me just do the same for a middle name so middle name I'm limiting the number of characters sitting
on middle space.
Name and date of birth would have similar rules for enrollment dates and surplus IDs anyway so this
date of birth and then the second step of this entire transformation process is to create a public plus
a partial plus and call it student and associate the Metro data class with it.
And you can look back at the previous school was understands and type it here into a data type and then
in brackets we see it type of sorry type off and then we spell out that it should be off type student
meta data.
And as our final act which probably could have come first anyway we want to make sure that our namespace
is the same as the namespace for our part.
So Target class and then having done all of this we can go ahead and continue with our development or
in debug and see if everything clicks.
Now when our students page loads you can start seeing the differences already you see that discernible
space between the last name first name date of enrolments.
So the labels have changed.
If we go to create news see that the labels for the form have changed the middle name dates of enrollment
will ever include the dates of birth on the create page as yet details so everywhere and that is dynamically
using that each time a helper that we pointed out is in details display name for or in the create we
have label for or in our index.
Next we have display name for everywhere that you have something like that by setting up or data annotations
and setting up our method class.
We will see the different labels that we set being displayed for our users and that is indeed and in
fact how you go about customizing what is displayed without being too intrusive.
And by leveraging the flexibility that this framework gives you.