c# – ASP.NET MVC自定义多字段验证

c# – ASP.NET MVC自定义多字段验证,第1张

概述我正在开发一个ASP.NET MVC 5.2.3自定义数据注释,以便在Visual Studio 2015中进行验证.它需要占用任意数量的字段并确保如果有一个值,它们都必须具有值;如果他们都是空的/空白,那应该没问题. 一些例子有所帮助: > ASP.NET MVC implement custom validator use IClientValidatable > MVC Form Valid 我正在开发一个ASP.NET MVC 5.2.3自定义数据注释,以便在Visual Studio 2015中进行验证.它需要占用任意数量的字段并确保如果有一个值,它们都必须具有值;如果他们都是空的/空白,那应该没问题.

一些例子有所帮助:

> ASP.NET MVC implement custom validator use IClientValidatable
> MVC Form Validation on Multiple Fields
> http://www.macaalay.com/2014/02/24/unobtrusive-client-and-server-side-age-validation-in-mvc-using-custom-data-annotations/

但是,我不确定如何进行客户端验证,其中您验证了未知数量的字段.

如何使用IClIEntValIDatable接口的GetClIEntValIDationRules()方法实现将其传递给客户端?

另外,如何将此新数据注释应用于视图模型的属性?它看起来像这样吗?

[Multiplerequired("AppNumber","UserID",/* more fIElds */),ErrorMessage = "Something..."][displayname("App #")]public int AppNumber { get; set; }[displayname("User ID")]public int UserID { get; set; }

这就是我可以使用MultiplerequiredAttribute自定义数据注释类:

public class MultiplerequiredAttribute : ValIDationAttribute,IClIEntValIDatable{    private Readonly string[] _fIElds;    public MultiplerequiredAttribute(params string[] fIElds)    {        _fIElds = fIElds;    }    protected overrIDe ValIDationResult IsValID(object value,ValIDationContext valIDationContext)    {        // If any fIEld has value,then all must have value        var anyHasValue = _fIElds.Any(f => !string.IsNullOrEmpty(f));        if (!anyHasValue) return null;        foreach (var fIEld in _fIElds)        {            var property = valIDationContext.ObjectType.GetProperty(fIEld);            if (property == null)                return new ValIDationResult($"Property '{fIEld}' is undefined.");            var fIEldValue = property.GetValue(valIDationContext.ObjectInstance,null);            if (string.IsNullOrEmpty(fIEldValue?.ToString()))                return new ValIDationResult(FormatErrorMessage(valIDationContext.displayname));        }        return null;    }    public IEnumerable<ModelClIEntValIDationRule> GetClIEntValIDationRules(ModelMetadata Metadata,ControllerContext context)    {        yIEld return new ModelClIEntValIDationRule        {            ErrorMessage = ErrorMessage,ValIDationType = "multiplerequired"        };    }}

谢谢.

解决方法 为了获得客户端验证,您需要使用规则ValIDationParameters属性的.Add()方法传递ModelClIEntValIDationRule中“其他属性”的值,然后编写客户端脚本以将规则添加到$.valIDator.

但首先,您的属性还需要解决其他一些问题.首先,只有在应用属性的属性值为null时才应执行foreach循环.其次,如果其中一个“其他属性”不存在,则返回ValIDationResult会让用户感到困惑和无意义,您应该忽略它.

属性代码应该是(注意我更改了属性的名称)

public class requiredIfAnyAttribute : ValIDationAttribute,IClIEntValIDatable{    private Readonly string[] _otherPropertIEs;    private const string _DefaultErrorMessage = "The {0} fIEld is required";    public requiredIfAnyAttribute(params string[] otherPropertIEs)    {        if (otherPropertIEs.Length == 0) // would not make sense        {            throw new ArgumentException("At least one other property name must be provIDed");        }        _otherPropertIEs = otherPropertIEs;        ErrorMessage = _DefaultErrorMessage;    }    protected overrIDe ValIDationResult IsValID(object value,ValIDationContext valIDationContext)    {        if (value == null) // no point checking if it has a value        {            foreach (string property in _otherPropertIEs)            {                var propertyname = valIDationContext.ObjectType.GetProperty(property);                if (propertyname == null)                {                    continue;                }                var propertyValue = propertyname.GetValue(valIDationContext.ObjectInstance,null);                if (propertyValue != null)                {                    return new ValIDationResult(FormatErrorMessage(valIDationContext.displayname));                }            }        }        return ValIDationResult.Success;    }    public IEnumerable<ModelClIEntValIDationRule> GetClIEntValIDationRules(ModelMetadata Metadata,ControllerContext context)    {        var rule = new ModelClIEntValIDationRule        {            ValIDationType = "requiredifany",ErrorMessage = FormatErrorMessage(Metadata.Getdisplayname()),};        / pass a comma separated List of the other propetIEs        rule.ValIDationParameters.Add("otherpropertIEs",string.Join(",",_otherPropertIEs));        yIEld return rule;    }}

然后脚本将是

sandtrapValIDation = {    getDependentElement: function (valIDationElement,dependentProperty) {        var dependentElement = $('#' + dependentProperty);        if (dependentElement.length === 1) {            return dependentElement;        }        var name = valIDationElement.name;        var index = name.lastIndexOf(".") + 1;        var ID = (name.substr(0,index) + dependentProperty).replace(/[\.\[\]]/g,"_");        dependentElement = $('#' + ID);        if (dependentElement.length === 1) {            return dependentElement;        }        // Try using the name attribute        name = (name.substr(0,index) + dependentProperty);        dependentElement = $('[name="' + name + '"]');        if (dependentElement.length > 0) {            return dependentElement.first();        }        return null;    }}$.valIDator.unobtrusive.adapters.add("requiredifany",["otherpropertIEs"],function (options) {    var element = options.element;    var othernames = options.params.otherpropertIEs.split(',');    var otherPropertIEs = [];    $.each(othernames,function (index,item) {        otherPropertIEs.push(sandtrapValIDation.getDependentElement(element,item))    });    options.rules['requiredifany'] = {        otherpropertIEs: otherPropertIEs    };    options.messages['requiredifany'] = options.message;});$.valIDator.addMethod("requiredifany",function (value,element,params) {    if ($(element).val() != '') {        // The element has a value so its OK        return true;    }    var isValID = true;    $.each(params.otherpropertIEs,item) {        if ($(this).val() != '') {            isValID = false;        }    });    return isValID;});
总结

以上是内存溢出为你收集整理的c# – ASP.NET MVC自定义多字段验证全部内容,希望文章能够帮你解决c# – ASP.NET MVC自定义多字段验证所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1232731.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存