客户端验证的自定义注释Asp。净MVC 4

时间:2021-12-14 16:39:18

I am referring this article:

我指的是这篇文章:

http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

which shows how to create custom annotation in Asp.Net MVC 2. However, the client side validation scripts, especially "MicrosoftMvcJQueryValidation" is not available in Asp.Net MVC4. I read it on one article it is part of Asp.Net Futures project. I want to hook up my client side validation using Jquery. In my project template script's folder, I see scripts named:

这说明了如何在Asp中创建自定义注释。净MVC 2。但是,客户端验证脚本,尤其是“MicrosoftMvcJQueryValidation”在Asp中是不可用的。净MVC4。我在一篇文章中读到它是Asp的一部分。净期货项目。我想用Jquery连接我的客户端验证。在我的project template脚本文件夹中,我看到了名为:

jquery.validate.min.js
jquery.validate.unobtrusive.min.js
jquery.unobtrusive-ajax.min.js

Is there any way I can make use of these existing scripts? or do I have to compulsorily download futures project?

我可以利用这些现有的脚本吗?还是我必须强制下载期货项目?

2 个解决方案

#1


14  

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.

这篇文章针对的是使用MicrosoftAjax的MVC 2。MVC 4不再包括MS Ajax文件,因为它们已经被弃用,而首选的方法是使用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>

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

这两个设置存在于web的appSettings部分。配置文件

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

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; }
}

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>

Update

更新

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

这里有一个自定义验证器的例子,我把它称为RateRequiredIfCustomIndexRate,这是它的javascript代码,因此它被添加到jquery验证中。

$("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");

#2


10  

The key thing missing here is that the server-side validator must implement the IClientValidatable interface:

这里缺少的关键是服务器端验证器必须实现IClientValidatable接口:

public class RateRequiredIfCustomIndexRateAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "raterequiredifcustomindexrate"
        };
    }
}

Once you do that, the client-side validation should be hooked up properly. You can verify this by making sure that your input field has an attribute "data-val-raterequiredifcustomindexrate" attribute.

这样做之后,客户端验证应该正确地连接起来。您可以通过确保输入字段具有属性“data- valraterequiredifcustomindexrate”属性来验证这一点。

#1


14  

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.

这篇文章针对的是使用MicrosoftAjax的MVC 2。MVC 4不再包括MS Ajax文件,因为它们已经被弃用,而首选的方法是使用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>

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

这两个设置存在于web的appSettings部分。配置文件

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

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; }
}

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>

Update

更新

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

这里有一个自定义验证器的例子,我把它称为RateRequiredIfCustomIndexRate,这是它的javascript代码,因此它被添加到jquery验证中。

$("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");

#2


10  

The key thing missing here is that the server-side validator must implement the IClientValidatable interface:

这里缺少的关键是服务器端验证器必须实现IClientValidatable接口:

public class RateRequiredIfCustomIndexRateAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "raterequiredifcustomindexrate"
        };
    }
}

Once you do that, the client-side validation should be hooked up properly. You can verify this by making sure that your input field has an attribute "data-val-raterequiredifcustomindexrate" attribute.

这样做之后,客户端验证应该正确地连接起来。您可以通过确保输入字段具有属性“data- valraterequiredifcustomindexrate”属性来验证这一点。