C# 布尔值、字符串和文件上载的RequiredIf验证属性
有人可以给我写一个验证属性的示例,该属性验证一个依赖字段,该字段可以是布尔值、字符串或HttpPostedFile值。我一直在寻找,但我尝试过的例子并不适用于所有这些情况。e、 或者,如果你能找出为什么我的页面在验证后没有提交-这是一个例子的链接 例如,1如果UserReferenceID为false,则使用部门图像C# 布尔值、字符串和文件上载的RequiredIf验证属性,c#,asp.net-mvc,validation,C#,Asp.net Mvc,Validation,有人可以给我写一个验证属性的示例,该属性验证一个依赖字段,该字段可以是布尔值、字符串或HttpPostedFile值。我一直在寻找,但我尝试过的例子并不适用于所有这些情况。e、 或者,如果你能找出为什么我的页面在验证后没有提交-这是一个例子的链接 例如,1如果UserReferenceID为false,则使用部门图像 public bool UserReferenceId { get; set; } [RequiredIf("UseReferenceId", false, ErrorMessa
public bool UserReferenceId { get; set; }
[RequiredIf("UseReferenceId", false, ErrorMessage="Error please select a Advert image")]
public HttpPostedFileBase DepartmentImageFile { get; set; }
例2
我一直在使用这段代码,但我的页面在验证完成后不会提交
data-val-requiredif="Url is required for advertisement url."
data-val-requiredif-dependentproperty="UseReferenceId" data-val-requiredif-targetvalue="false"
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
protected RequiredAttribute _innerAttribute;
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public bool AllowEmptyStrings
{
get
{
return _innerAttribute.AllowEmptyStrings;
}
set
{
_innerAttribute.AllowEmptyStrings = value;
}
}
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
_innerAttribute = new RequiredAttribute();
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
// trim spaces of dependent value
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
{
dependentValue = null;
}
}
// compare the value against the target value
if ((dependentValue == null && TargetValue == null) ||
(dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
{
// match => means we should try validating this field
if (!_innerAttribute.IsValid(value))
// validation failed - return an error
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
}
data val requiredif=“广告Url需要Url。”
数据值requiredif dependentproperty=“UserReferenceId”数据值requiredif targetvalue=“false”
公共类requireditAttribute:ValidationAttribute,IClientValidable
{
受保护的RequiredAttribute\u innerAttribute;
公共字符串依赖属性{get;set;}
公共对象TargetValue{get;set;}
公共场所允许吸烟
{
收到
{
返回_innerAttribute.AllowEmptyStrings;
}
设置
{
_innerAttribute.AllowEmptyStrings=值;
}
}
public requirediftAttribute(字符串相关属性,对象targetValue)
{
_innerAttribute=新的RequiredAttribute();
DependentProperty=DependentProperty;
TargetValue=TargetValue;
}
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
//获取对此验证所依赖的属性的引用
var containerType=validationContext.ObjectInstance.GetType();
var field=containerType.GetProperty(DependentProperty);
如果(字段!=null)
{
//获取依赖属性的值
var dependentValue=field.GetValue(validationContext.ObjectInstance,null);
//从属值的修剪空间
if(dependentValue!=null&&dependentValue为字符串)
{
dependentValue=(dependentValue作为字符串).Trim();
如果(!AllowEmptyStrings&&(dependentValue作为字符串)。长度==0)
{
dependentValue=null;
}
}
//将该值与目标值进行比较
if((dependentValue==null&&TargetValue==null)||
(dependentValue!=null&(TargetValue.Equals(“*”)| | dependentValue.Equals(TargetValue)))
{
//match=>表示我们应该尝试验证此字段
如果(!\u innerAttribute.IsValid(值))
//验证失败-返回错误
返回新的ValidationResult(FormatErrorMessage(validationContext.DisplayName),new[]{validationContext.MemberName});
}
}
返回ValidationResult.Success;
}
公共虚拟IEnumerable GetClientValidationRules(ModelMetadata元数据、ControllerContext上下文)
{
var规则=新ModelClientValidationRule
{
ErrorMessage=FormatErrorMessage(metadata.GetDisplayName()),
ValidationType=“requiredif”,
};
string depProp=BuildDependentPropertyId(元数据,上下文为ViewContext);
//找到我们所依赖的控件的值;
//如果是bool,则将其格式化为javascript样式
//(默认值为True或False!)
字符串targetValue=(targetValue??).ToString();
如果(目标值为布尔)
targetValue=targetValue.ToLower();
rule.ValidationParameters.Add(“dependentproperty”,depProp);
规则.ValidationParameters.Add(“targetvalue”,targetvalue);
收益率-收益率规则;
}
私有字符串BuildDependentPropertyId(ModelMetadata元数据,ViewContext)
{
//生成属性的ID
string depProp=viewContext.ViewData.TemplateInfo.GetFullHtmlFieldDid(DependentProperty);
//不幸的是,这将在开头追加当前字段的名称,
//因为TemplateInfo的上下文已经附加了这个字段名
//想要获得更高一级的上下文(即在当前属性之外,
//它是包含对象,因此与从属属性处于同一级别。
var thisField=metadata.PropertyName+“\uux”;
if(depProp.StartsWith(此字段))
//再把它剥掉
depProp=depProp.Substring(thisField.Length);
返回depProp;
}
}
您是否考虑过每个用例都有一个ValidationAttribute?是的,我一直在学习一个教程,但在验证完成后页面不会提交
data-val-requiredif="Url is required for advertisement url."
data-val-requiredif-dependentproperty="UseReferenceId" data-val-requiredif-targetvalue="false"
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
protected RequiredAttribute _innerAttribute;
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public bool AllowEmptyStrings
{
get
{
return _innerAttribute.AllowEmptyStrings;
}
set
{
_innerAttribute.AllowEmptyStrings = value;
}
}
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
_innerAttribute = new RequiredAttribute();
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
// trim spaces of dependent value
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
{
dependentValue = null;
}
}
// compare the value against the target value
if ((dependentValue == null && TargetValue == null) ||
(dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
{
// match => means we should try validating this field
if (!_innerAttribute.IsValid(value))
// validation failed - return an error
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
}