Knockout + mvc 3 + Validation

前端 未结 4 707
自闭症患者
自闭症患者 2020-12-08 04:23

In the controller I would like to be able to get to the client validation rules of the model. I\'ve attached some attributes using data annotations and would like to be able

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 04:26

    On the model use attributes validation that you like:

     public class ModelWithValidation
     {
        public int Id { get; set; }
    
        [Required]
        public string Name { get; set; }
     }
    

    In mvc forms

    @using( Html.BeginForm())
    {    
         @Html.TextBoxFor(m => m.Name, new {data_bind = "value: name"})
         @Html.ValidationMessageFor(m => m.Name)
    }
    

    In jQuery test if form is valid onSubmit or in knockout save function call the next code to validate input. You must include jQuery.unobtrusive* and jQuery.validate* libraries. Don't forget to validate input on server side also!

    var form = $("form");
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(form);
    
    $("form").valid() //true false 
    

提交回复
热议问题