我的表单有两个模型属性,即Max和Min,它们负责表单中的任何Max或Min值,我对其进行了验证以确保它们是小数并存在,并且还验证了范围
[Required]
[RegularExpression("^\\d+(.\\d+){0,1}$", ErrorMessage = "Invalid Value")]
[MaxMinRange("Allowed range (0-100)")]
public string Minimum { get; set; }
[Required]
[RegularExpression("^\\d+(.\\d+){0,1}$", ErrorMessage = "Invalid Value")]
[MaxMinRange("Allowed range (0-100)")]
public string Maximum { get; set; }
这是我针对范围的自定义验证器
public class MaxMinRangeAttribute : ValidationAttribute
{
private String ErrorMessage { get; set; }
public MaxMinRangeAttribute(String errormessage)
{
this.ErrorMessage = errormessage;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
if (value != null)
{
double maxmin;
bool isDouble = Double.TryParse(value.ToString(), out maxmin);
if (isDouble && Convert.ToDouble(value.ToString()) > 100)
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
}
但是,我的View / cshtml页面中的“最大”和“最小”模型属性代表了不同的父类,例如化学成分的百分比或毫米
(化学成分百分比)
<td>
<input type="text" class="form-control" asp-for="BIS232Request.JSONData.ChemicalComposition[20].Value.Minimum" />
<span asp-validation-for="BIS232Request.JSONData.ChemicalComposition[20].Value.Minimum" class="alert-danger"></span>
</td>
<td>
<input type="text" class="form-control" asp-for="BIS232Request.JSONData.ChemicalComposition[21].Value.Minimum" />
<span asp-validation-for="BIS232Request.JSONData.ChemicalComposition[21].Value.Minimum" class="alert-danger"></span>
</td>
毫米
<td>
<input type="text" class="form-control" asp-for="BIS232Request.JSONData.ProductDimensions[0].Value.Minimum" />
<span asp-validation-for="BIS232Request.JSONData.ProductDimensions[0].Value.Minimum" class="alert-danger"></span>
</td>
<td>
<input type="text" class="form-control" asp-for="BIS232Request.JSONData.ProductDimensions[1].Value.Minimum" />
<span asp-validation-for="BIS232Request.JSONData.ProductDimensions[1].Value.Minimum" class="alert-danger"></span>
</td>
百分比显然不应大于100;但是,毫米可以是
我的问题是,如何根据父类,额外的属性或某些其他参数来不同地验证相同的模型属性?
如何验证百分比不大于100的最大值/最小值,而忽略此最大值/最小值毫米的验证?
非常感谢您的帮助
答案 0 :(得分:0)
我们最终更新了模型(无法避免)。我们已经为百分比创建了一个额外的属性
public class MaxMin
{
[Required]
[RegularExpression("^\\d+(.\\d+){0,1}$", ErrorMessage = "Invalid Value")]
public string Minimum { get; set; }
[Required]
[RegularExpression("^\\d+(.\\d+){0,1}$", ErrorMessage = "Invalid Value")]
public string Maximum { get; set; }
}
public class MaxMinPercentage
{
[Required]
[RegularExpression("^\\d+(.\\d+){0,1}$", ErrorMessage = "Invalid Value")]
[MaxMinRange("Allowed range (0-100)")]
public string Minimum { get; set; }
[Required]
[RegularExpression("^\\d+(.\\d+){0,1}$", ErrorMessage = "Invalid Value")]
[MaxMinRange("Allowed range (0-100)")]
public string Maximum { get; set; }
}