1.10.4.Implementing Client-side Validation

  • 1.Add @Scripts.Render("~/bundles/jqueryval") to New.cshtml

  • 2.Customerize validator

  • 3.Move submit function in $("#newRental").validate({ submitHandler: function () {}});

@section Scripts
{
 @Scripts.Render("~/bundles/jqueryval");
 <script>
  $(document).ready(function () {


   $.validator.addMethod("validationCustomer", function () {
    return vm.customerId && vm.customerId !== 0;
   }, "Please select a valid customer");

   $("#newRental").validate({
    submitHandler: function () {
     $.ajax({
      url: "/api/newRental",
      method: "post",
      data: vm
     })
      .done(function () {
       toastr.success("Rental successfully recorded");
      })
      .fail(function () {
       toastr.error("Something unexpected happened");
      });
    }
  • 4.Modify input property

      <input id ="customer" name ="customer" data-rule-validationCustomer= "true" required type = "text" value="" class="form-control">
  • 5.Clear input and viewModel after submitting

      var validator = $("#newRental").validate({
      submitHandler: function () {
       $.ajax({
        url: "/api/newRental",
        method: "post",
        data: vm
       })
        .done(function () {
         toastr.success("Rental successfully recorded");
         $('#customer').typeahead("val", "")
         $('#movie').typeahead("val", "")
         $('#movie').empty()
    
         vm = { movieIdsP: [] };
         validator.resetForm();
        })
        .fail(function () {
         toastr.error("Something unexpected happened");
        });
    
       return false;
      }

Last updated