【问题标题】:How can I send a message to property validator İsvalid in fluentvalidation?如何在 fluentvalidation 中向属性验证器 İsvalid 发送消息?
【发布时间】:2022-03-08 16:54:02
【问题描述】:

hello fluent 验证已更新至 10.3.6 版,但之前在properyvalidator 中工作的 SetMessage 函数不再工作,我应该改用什么?

    public class TcknOrVknPropValidator : PropertyValidator
    {
        public TcknOrVknPropValidator() : base()
        {

        }

        protected override bool IsValid(PropertyValidatorContext context)
        {
            var propertyValue = context.PropertyValue as string;
            if (string.IsNullOrWhiteSpace(propertyValue))
            {
                SetErrorMessage("Tc veya Vergi No Geçersiz");//this function not found now
               
                return false;
            }

            if (propertyValue.Length < 10 || propertyValue.Length > 11)
            {

                SetErrorMessage("Tc Veya Vergi No Eksik Yada Hatalı");
                return false;
            }

           return true;
}

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc fluentvalidation


    【解决方案1】:

    在新版本中有如下用法

    public class VisitIdValidator<T, TCollectionElement> : PropertyValidator<T, TCollectionElement>
    {
    
        public VisitIdValidator()
        {
    
        }
    
        public override bool IsValid(ValidationContext<T> context, TCollectionElement visitId)
        {
            if (visitId==null || string.IsNullOrEmpty(visitId.ToString()))
            {
                context.MessageFormatter.AppendArgument("NotNull", visitId);
                return false;
            }
    
            return true;
        }
    
        public override string Name => "ListCountValidator";
    
        protected override string GetDefaultMessageTemplate(string errorCode)
            => "{PropertyName} notnull";
    }
    

    使用

     RuleFor(x => x.VisitId).SetValidator(new VisitIdValidator<SavePhoneRequestModel,string>());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多