MVC不显眼的验证

问题描述 投票:1回答:2

我想在我的MVC应用程序上使用不显眼的验证。我创造了课程

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
    private const string _defaultErrorMessage = "{0} is required";

    private string _targetPropertyName;
    private bool _targetPropertyCondition;

    public RequiredIfAttribute(string targetPropertyName, bool targetPropertyCondition)
        : base(_defaultErrorMessage)
    {
        this._targetPropertyName = targetPropertyName;
        this._targetPropertyCondition = targetPropertyCondition;
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, _targetPropertyName, _targetPropertyCondition);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        bool result = false;
        bool propertyRequired = false;
        var targetProperty = validationContext.ObjectType.GetProperty(_targetPropertyName);

       var targetPropertyValue = (bool)targetProperty.GetValue(validationContext.ObjectInstance, null);

        if (targetPropertyValue == _targetPropertyCondition)
        {
            propertyRequired = true;
        }

        if (propertyRequired)
        {
            if (value == null)
            {
                var message = FormatErrorMessage(validationContext.DisplayName);

                return new ValidationResult(message);  
            }
        }

        return null;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();

        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "requiredif";
        rule.ValidationParameters.Add("targetpropertyname", this._targetPropertyName);
        rule.ValidationParameters.Add("targetpropertyvalue", this._targetPropertyCondition.ToString().ToLower());

        yield return rule;
    }   
}

我在客户端有验证功能

$(function () {
    $.validator.addMethod("requiredif", function (value, element, param) {

       if ($(param.propertyname).is(':checked').toString() == param.propertyvalue) {
           if (!this.depend(param, element))
               return "dependency-mismatch";
           switch (element.nodeName.toLowerCase()) {
               case 'select':
                   var val = $(element).val();
                   return val && val.length > 0;
               case 'input':
                   if (this.checkable(element))
                       return this.getLength(value, element) > 0;
               default:
                   return $.trim(value).length > 0;
           }
       }

       return true;
    });


    $.validator.unobtrusive.adapters.add("requiredif", ["targetpropertyname", "targetpropertyvalue"], function (options) {
       if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
           options.rules["requiredif"] = {
               propertyname: "#" + options.params.targetpropertyname,
               propertyvalue: options.params.targetpropertyvalue
           };
           options.messages["requiredif"] = options.message;
       }
    });
} (jQuery));

但这并没有验证。为什么?

model-view-controller validation unobtrusive-validation
2个回答
0
投票

如果你有smth,请检查你的web.config。像这样

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

当然,您应该在模型中使用适当的属性


0
投票

使用有效的js文件。

https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js

也可以通过控制器:

HtmlHelper.ClientValidationEnabled = true; HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

© www.soinside.com 2019 - 2024. All rights reserved.