輸入的最大值必須大于最小值。現在我的代碼在 Max 與 Min 相同時顯示錯誤訊息(使用比較)。是否有可用于將一個輸入與另一個輸入進行比較的驗證器?
我的資料.cs:
public class MyData
{
[Required]
public double Min { get; set; }
[Compare("Min", ErrorMessage = "checks for matching min value")]
public double Max { get; set; }
}
形式.剃刀:
<div class="modal-body">
<EditForm EditContext="@context">
<DataAnnotationsValidator />
<label class="form-label" for="Min">Min</label>
<input class="form-control" @bind=model.Min type="text">
<label class="form-label" for="Max">Max</label>
<input class="form-control" @bind=model.Max type="text">
<ValidationMessage For="@(() => model.Max)" />
</EditForm>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" @onclick="() => Done()">Apply</button>
</div>
@code {
private MyData model = new MyData();
private EditContext context;
protected override void OnInitialized()
{
model = (MyData)(modalDialog?.ModalRequest.InData ?? new MyData());
context = new EditContext(model);
}
private void Done()
{
if (@model.Max < @model.Min)
{
context.Validate(); @*this displays error message*@
}
else
{
modalDialog?.Close(ModalResult.OK(model));
}
}
uj5u.com熱心網友回復:
要使用您需要創建自定義驗證屬性來驗證大于或小于另一個屬性而不是值Data Annotations,如下所示:
大于屬性
// Custom attribute for validating greater than other property
public class GreaterThan : ValidationAttribute
{
private readonly string _comparisonProperty;
public GreaterThan(string comparisonProperty)
{
_comparisonProperty = comparisonProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorMessage = ErrorMessageString;
var currentValue = (double)value; // cast to double same as property type
var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
if (property == null)
throw new ArgumentException("Property with this name not found");
var comparisonValue = (double)property.GetValue(validationContext.ObjectInstance); // cast to property type
// comparison condition
if (currentValue < comparisonValue)
return new ValidationResult(ErrorMessage);
return ValidationResult.Success;
}
}
LessThan屬性您可以使用上面相同的代碼通過將名稱和比較條件更改
為來創建屬性。LessThancurrentValue > comparisonValue
下面是一個關于如何用于Data Annotations驗證模型并在表單中顯示驗證錯誤的示例。它包括GreaterThan自定義驗證屬性以及其他常見的驗證屬性。

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521186.html
標籤:验证剃刀西装外套
上一篇:列值中的Sparkregex'COIN'->rlike方法
下一篇:golang中的輸入驗證
