2014-03-14 62 views
0

我想顯示其驗證寫入視圖模型爲我的DOM元素驗證消息:使用ASP.NET MVC驗證的jQuery

我的視圖模型代碼如下::

public class HotelDetailViewModel 
    { 
     public long DocumentHotelID { get; set; } 
     [Required(ErrorMessage = "Please enter Check In Date")] 
     public string CheckInDate { get; set; } 
     [Required(ErrorMessage = "Please enter Room Type")] 
     public string RoomType { get; set; } 
     [Required(ErrorMessage = "Please enter Nights")] 
     public int Nights { get; set; } 
    } 

我有還使用了剃刀驗證器:

@Html.ValidationMessageFor(Model => Model.CheckInDate) 

但我想在客戶端本身進行驗證,而不進行任何提交。 因爲我在頁面上有兩種形式,只有一種形式可以提交,而其他我必須在客戶端使用Jquery, 來做一些事情。 在此先感謝。

回答

1

要啓用與jQuery驗證插件急於驗證,在您的視圖中使用此代碼

$('#myform').validate({ 
onfocusout: function(element) { 
    $(element).valid(); 
} 
}); 
0

在MVC中,以支持在客戶端驗證DataAnnotation,你就必須把這個JavaScript文件 ** jquery.unobtrusive-ajax.js,jquery.validate.min.js,jquery.validate.unobtrusive.min.js

這是可以呈現爲

@Scripts.Render("~/bundles/jqueryval") 
+0

正確讀取的問題,然後回答。 – Rahul

+0

這個JavaScript文件將驗證模型,而無需提交 – 111

0

如果您準備使用jquery.validate.min.js,則可以在客戶端添加驗證規則。

<script src="jquery.validate.min.js" type="text/javascript"></script> 

@using (Html.BeginForm("action", "controller", new { Id = "ClientForm" }, FormMethod.Post)) 
{ 

    @Html.LabelFor(m => m.UserName) 
    @Html.TextBoxFor(m => m.UserName) 

    <input type="submit" value="Log in" /> 
} 

添加驗證規則

<script> 
    $("#ClientForm").validate({ 
     rules: { 
      'UserName': { 
       required: true, 
       maxlength: 20 
      } 
     }, 
     messages: { 
      'UserName': { 
       required: 'Title required', 
       maxlength: 'Must be under 20 characters' 
      } 
     } 
    }); 
</script>