我想要确保一个简单的字段大于某个数字。注意事项:
这里发生了什么:
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
行(通过调试器跟踪确认)。我希望"必须大于"在视图中调用ValidationSummary之后出现错误,因为GreaterThan类确定-5不大于零。知道为什么不是这样吗?
这是我的自定义验证类:
public class MyViewModel
{
[Required]
[GreaterThan(0)]
[DisplayName("Hours")]
public string Hours { get; set; }
}
public class GreaterThan : ValidationAttribute
{
private readonly float _lowerBound;
public GreaterThan(int lowerBound) : base("{0} must be greater than " + lowerBound + ".")
{
_lowerBound = lowerBound;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
float result;
if (float.TryParse(value.ToString(), out result) && result > _lowerBound)
{
return ValidationResult.Success;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
观点:
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post))
{
@Html.ValidationSummary()
<fieldset>
@Html.LabelFor(m => m.Hours)
@Html.EditorFor(m => m.Hours)
<button type="submit">Submit</button>
</fieldset>
}
动作:
public ActionResult MyAction(MyViewModel model)
{
try
{
// [...] Some irrelevant stuff
return RedirectToAction("Index", "MyController");
}
catch (Exception exception)
{
// [...] Handle the exception
return RedirectToAction("Index", "MyController");
}
}
答案 0 :(得分:0)
为什么它是字符串类型?如果你使用了decimal或int,你可以节省很多工作。有一个内置范围验证。
范围验证代码
[Range(typeof(decimal), "0", "99999", ErrorMessage = "{0} must be between {1} to {2}")]
[Required]
[DisplayName("Hours")]
public decimal Hours { get; set; }