且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

客户端验证定制标注Asp.Net MVC 4

更新时间:2022-05-31 22:45:21

这条是针对MVC 2的使用MicrosoftAjax。 MVC 4不再包括该MS的Ajax文件,因为它们已经德precated和preferred方法是使用jquery

That article is specific to MVC 2 which used MicrosoftAjax. MVC 4 no longer includes the MS Ajax files as they have been deprecated and the preferred method is to use jquery.

要验证您的设置,确保这些脚本是在你的布局

To verify your settings, make sure these scripts are in your layout

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

和这两个设置是present在appSettings部分在你的web.config文件

And these two settings are present in the appSettings section in your web.config file

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

所以,当你将数据添加注释到您的ViewModels你的客户端和服务器端验证这两个

So when you add data annotations to your ViewModels you get client side and server side validation both

public class MyModel 
{
    [Required]
    [StringLength(30)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(30)]
    public string LastName { get; set; }
}

在你看来只是确保你有code这样

In your view just make sure you have code like this

<div>
    @Html.LabelFor(model => model.FirstName)
</div>
<div>
    @Html.TextBoxFor(model => model.FirstName) <br/>
    @Html.ValidationMessageFor(model => model.FirstName)
</div>

<div>
    @Html.LabelFor(model => model.LastName)
</div>
<div>
    @Html.TextBoxFor(model => model.LastName) <br/>
    @Html.ValidationMessageFor(model => model.LastName)
</div>

更新

下面就是我呼吁RateRequiredIfCustomIndexRate自定义验证程序的示例 这是它的JavaScript端,以便它被添加到jQuery验证

Here's an example of a custom validator that I have called RateRequiredIfCustomIndexRate This is the javascript side of it so that it gets added to jquery validation

$("document").ready(function () {

    var isCustomRateRequired = document.getElementById("IsCustomRateRequired");

    isCustomRateRequired.onchange = function () {
        if (this.checked) {
            $('#Rate').attr('disabled', 'disabled');
            $('#Rate').val('');
        }
        else {
            $('#Rate').removeAttr('disabled');
        }
    };
});

jQuery.validator.addMethod("raterequiredifcustomindexrate", function (value, element, param) {
    var rateRequired = $("#CustomRateRequired").val();
    if (rateRequired && value == "") {
        return false;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.addBool("raterequiredifcustomindexrate");