私は次のような単純なモデルを持っています:
[Validator(typeof(EntryModelValidator))]
public class EntryModel : BaseNopEntityModel
{
public virtual string ProductActionValue { get; set; }
}
モデルの保存を検証するために FluentValidation を使用しています。問題は、ユーザーがフォームに値を保存するときに、特定の状況で ProductActionValue を int として保存する必要があることです (もちろん常に文字列として保存されますが、int として解析可能である必要があります)。
値が空でないことを保証する次の検証ルールがあります。
RuleFor(x => x.ProductCriteriaValue)
.NotEmpty()
.WithMessage(localizationService.GetResource("Common.FieldRequired"));
次のルールを追加して、int として検証しようとしました。
RuleFor(x => Int32.Parse(x.ProductCriteriaValue))
.GreaterThanOrEqualTo(1)
.When(x => (ProductCriteriaTypes)x.ProductCriteriaTypeId == ProductCriteriaTypes.ProductCreatedGreaterThanXDays || (ProductCriteriaTypes)x.ProductCriteriaTypeId == ProductCriteriaTypes.ProductCreatedLessThanXDays)
.WithMessage(localizationService.GetResource("Common.FieldRequired"));
しかし、これは FluentValidation ランタイム エラーをスローするだけです。とにかくこれを達成することはありますか?
前もってありがとうアル
AHMAD のソリューションを反映するように更新:
{
RuleFor(x => x.ProductCriteriaValue)
.Must(BeANumber)
.WithMessage(localizationService.GetResource("Common.FieldRequired"));
}
private bool BeANumber(string value)
{
int result;
if (Int32.TryParse(value, out result))
{
return result >= 1;
}
return false;
}