Part 88 - Unobtrusive validation in asp.net mvc

Client side validation in asp.net mvc is unobtrusive. To turn on client side validation and unobtrusive JavaScript, make sure the following 2 keys under appSettings element within web.config file are turned on. This will turn on client side validation and unobtrusive JavaScript for the entire application.
<appSettings>
  <add key="ClientValidationEnabled" value="true" />
   < add   key ="UnobtrusiveJavaScriptEnabled"  value ="true" />

</appSettings> 

Is it possible to turn these features on/off using code?
Yes, the features can be enabled or disabled in Application_Start() event handler in Global.asax as shown below. This will turn on client side validation and unobtrusive JavaScript for the entire application. 
protected void Application_Start()
{
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
    HtmlHelper.ClientValidationEnabled = true;
}

Is it possible to turn these features on/off for a specific view?
Yes, include the following code, on a view where you want to enable/disable these features.
@{
    Html.EnableClientValidation(true);
    Html.EnableUnobtrusiveJavaScript(true);
}

How is Unobtrusive validation implemented in asp.net mvc?
Using "data" attributes. For example, if we use "Required" attribute, on Name property and if we enable client side validation and unobtrusive JavaScript, then the generated HTML for "Name" field is as shown below.
<input class="text-box single-line" 
      data-val="true" 
      data-val-required="The Name field is required." 
      id="Name" 
      name="Name" 
      type="text" 
      value="Sara Nan" />

data-val=”true”, indicates that the unobtrusive validation is turned on for this element.
data-val-required="The Name field is required.", indicates that the "Name" field is required and the associated error message will be displayed if the validation fails. These data attributes are used by jQuery validation plugin for client side validation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值