[1/7] Become a Full Stack .NET Developer: Implementing Validation
In this part of the module we focused on server and client side validation techniques we could employ on our newly created Add A Gig form for GigHub.
We began by adding the [Required] Data Annotation to the getter and setter methods in the properties found in the GigFormViewModel (Venue, Date, Time, Genre). The benefit of Data Annotations is that we get both the server and client side validation in one, even though you need to add a JQueryval bundle to your page to enable client side validation.
Following this we went to the view for this model and added placeholders for validation messages such as @HTML.ValidationMessageFor(m => m.Venue) etc...
Now we needed to modify the GigsController with some validation logic. We added this bit of code to our Create (GigFormViewModel viewModel) -
if (!ModelState.IsValid) return View("Create", viewModel);
So if the ModelState (which is a property of the Controller) is not valid we will return the Create View with the viewModel passed to this method. So when the view is returned all existing entered values will be in the form fields with incorrect validation notifications to alert the user.
We tried to run our code by putting in no values into our Add a Gig form and see what happened and we were greeted by an error exception concerning a string not being valid as DateTime value. This is because when ASP.NET tries to call the DateTime property in the Create Action of our GigsController it uses a technique known as Reflection to construct the viewModel and return it to the view. To solve this issue we needed to turn the DateTime property into a method in the GigFormViewModel. We removed the DateTime getter and setter method here and instead placed this code -
public DateTime GetDateTime { get { return DateTime.Parse(string.Format(" ", Date, Time)); } }
We now tried our form validation test again by adding no inputs to any of the fields and this time validation worked as expected.
So far in this module we have concerned ourselves with server-side validation. We would now turn to addressing what could be done on the client side of things. One big advantage of applying client side validation is that we cut down on the number of back and forth requests between the server and client in validating a user's data.
To enable client side validation in a ASP.NET project, you must add the JQueryVal bundle to any pages or views that will require validation. So at the bottom of our Add a Gig view we added this code -
@section scripts { @Scripts.Render("~/bundles/jqueryval") }
We don't yet have client side validation date and time, but will implement them in a later module. We finished this module by once agin commiting our code tot he repository and moving on to the enxt module.