自定义验证属性中的客户端验证-ASP.NET MVC 4

2021/01/04 16:11 · jquery ·  · 0评论

我在Internet上关注了一些文章和教程,以创建一个自定义验证属性,该属性还支持asp.net mvc 4网站中的客户端验证。这是我到目前为止所拥有的:

RequiredIfAttribute.cs

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] //Added
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string condition;
    private string propertyName; //Added

    public RequiredIfAttribute(string condition)
    {
        this.condition = condition;
        this.propertyName = propertyName; //Added
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(this.propertyName); //Added
        Delegate conditionFunction = CreateExpression(validationContext.ObjectType, _condition);
        bool conditionMet = (bool)conditionFunction.DynamicInvoke(validationContext.ObjectInstance);

        if (conditionMet)
        {
            if (value == null)
            {
                return new ValidationResult(FormatErrorMessage(null));
            }
        }

        return ValidationResult.Success;
    }

    private Delegate CreateExpression(Type objectType, string expression)
    {
        LambdaExpression lambdaExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(objectType, typeof(bool), expression); //Added
        Delegate function = lambdaExpression.Compile();
        return function;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var modelClientValidationRule = new ModelClientValidationRule
        {
            ValidationType = "requiredif",
            ErrorMessage = ErrorMessage //Added
        };

        modelClientValidationRule.ValidationParameters.Add("param", this.propertyName); //Added
        return new List<ModelClientValidationRule> { modelClientValidationRule };
    }
}

然后我将此属性应用于此类的属性

[RequiredIf("InAppPurchase == true", "InAppPurchase", ErrorMessage = "Please enter an in app purchase promotional price")] //Added "InAppPurchase"
public string InAppPurchasePromotionalPrice { get; set; }

public bool InAppPurchase { get; set; }

所以我想做的是显示一条错误消息,当InAppPurchase字段为true(这表示在表单中选中)时,要求输入InAppPurchasePromotionalPrice字段。以下是相关代码表的视图:

<div class="control-group">
                <label class="control-label" for="InAppPurchase">Does your app include In App Purchase?</label>
                <div class="controls">
                    @Html.CheckBoxFor(o => o.InAppPurchase)
                    @Html.LabelFor(o => o.InAppPurchase, "Yes")
                </div>
            </div>
            <div class="control-group" id="InAppPurchasePromotionalPriceDiv" @(Model.InAppPurchase == true ? Html.Raw("style='display: block;'") : Html.Raw("style='display: none;'"))>
                <label class="control-label" for="InAppPurchasePromotionalPrice">App Friday Promotional Price for In App Purchase: </label>
                <div class="controls">
                    @Html.TextBoxFor(o => o.InAppPurchasePromotionalPrice, new { title = "This should be at the lowest price tier of free or $.99, just for your App Friday date." })
                    <span class="help-inline">
                        @Html.ValidationMessageFor(o => o.InAppPurchasePromotionalPrice)
                    </span>
                </div>
            </div>

这段代码可以正常工作,但是当我提交表单时,需要在服务器上发送完整的帖子以显示消息。因此,我创建了JavaScript代码来启用客户端验证:

requiredif.js

(function ($) {
    $.validator.addMethod('requiredif', function (value, element, params) {
        /*var inAppPurchase = $('#InAppPurchase').is(':checked');

        if (inAppPurchase) {
            return true;
        }

        return false;*/

        var isChecked = $(param).is(':checked');

        if (isChecked) {
            return false;
        }

        return true;
    }, '');

    $.validator.unobtrusive.adapters.add('requiredif', ['param'], function (options) {
        options.rules["requiredif"] = '#' + options.params.param;
        options.messages['requiredif'] = options.message;
    });
})(jQuery);

这是我在msdn和教程中发现的建议方法

当然,我也以以下形式插入了所需的脚本:

  1. jquery.unobtrusive-ajax.min.js
  2. jquery.validate.min.js
  3. jquery.validate.unobtrusive.min.js
  4. requiredif.js

但是...客户端验证仍然不起作用。那你能帮我找到我想念的东西吗?提前致谢。

看看这个:http : //thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/

使用本教程,我的自定义验证代码可以正常运行。我可以在代码中发现的唯一区别是创建$.validator.unobtrusive.adapters.add函数的方式。参数有些不同,但是可能的问题是,您尚未定义rule适配器一部分。

尝试使用如下所示的内容:

$.validator.unobtrusive.adapters.add("requiredif", ["requiredif"], function (options) {
    options.rules["requiredif"] = "#" + options.params.requiredif;
    options.messages["requiredif"] = options.message;
});

或这个

$.validator.unobtrusive.adapters.add("requiredif", function (options) {
    options.rules["requiredif"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers
    options.messages["requiredif"] = options.message;
});

关于rule(摘自链接):

此HTML元素的jQuery规则数组。预期适配器会将要附加的特定jQuery Validate验证器的项目添加到此规则数组。名称是jQuery Validate规则的名称,值是jQuery Validate规则的参数值。

值得注意的是,该[RequiredIf]属性需要添加到视图模型的第二个表单字段中,以便客户端验证起作用。

本文地址:http://jquery.askforanswer.com/zidingyiyanzhengshuxingzhongdekehuduanyanzheng-asp-net-mvc-4.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!