简体   繁体   中英

ASP.NET MVC5: Unobtrusive validation during the filling out of the form field

I want to make the validation element launched during the filling out of the form field.
If I create a simple MVC application that contains simple model:

public class SimpleModel
  {
    [RegularExpression("[A-Z][a-z]+")]
    [Required]
    public string FirstName { get; set; }

    [RegularExpression("[A-Z][a-z]+")]
    [Required]
    public string LastName { get; set; }
  }


For this model I created the corresponding Controller and View(Razor using template Edit) for this model.
At this time, everything worked as it should. But only when clicking on the Save button(submitting the form), not during filling the field. That's why I wanted to implement action onkeyup of the validator in script section:

@section Scripts
{
  @Scripts.Render("~/bundles/jqueryval")

  <script type="text/javascript">

    $('form').validate(
      {
        onkeyup: function (element)
        {
          $.validator.unobtrusive.parseElement(element, true);
        }
      });

  </script>
}


But it does not work and the original validation also does not work(now if i click the save, the form is submited as valid altrough fields are not filled or are filled in incorrectly).
And the original validation does not work if I use only $('form').validate(); or $('form').valid(); command. And maybe it is interesting that $('form').valid(); returns true although form is not filled and thus is not valid.

The solution is quite easy. Just realize, that validation using a script it is possible after initialization of the unobtrusive. This initialization is performed by registering new jquery ready function - in jquery.validate.unobtrusive.js at the bottom you find this code:

$(function () {
  $jQval.unobtrusive.parse(document);
});

Therefore, if it has to carry out additional initialization, so they must create own ready function and insert the necessary code.

For the purpose referred to in the question above, you can use this code:

@section Scripts 
{
  @Scripts.Render("~/bundles/jqueryval")

  <script type="text/javascript">

    $(function ()
    {
      var validator = $('form').validate();
      validator.form();
    });

  </script>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM