Skip to content
/ FluentValidation Public
  • Notifications You must be signed in to change notification settings
  • Fork 1.2k
  • Star 8.9k
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jump to bottom

Error when I pass my object to validate equal null #795

Closed
raffaelmiranda opened this issue Jun 20, 2018 · 9 comments
Closed

Error when I pass my object to validate equal null #795

raffaelmiranda opened this issue Jun 20, 2018 · 9 comments

Comments

@raffaelmiranda
Copy link

raffaelmiranda commented Jun 20, 2018

Hello everyone

I'm sorry I do not speak English and also if this channel is not considered appropriate for clarification of doubt. I am building a WebApi in .Net core 2.0 using version 7.5.2.

A validation that I must do is when my client that will consume my WebApi, should check if the object that arrived is null and for this I did the following validation

My validations

public class FaturaDtoValidator: AbstractValidator<FaturaDto>
   {
       public FaturaDtoValidator()
       {


           RuleFor(fatura => fatura).NotNull().WithMessage(Mensagem.FATURA_OBRIGATORIO);

           RuleFor(fatura => fatura.Itens).SetCollectionValidator(new ContratoItemDtoValidator());
           RuleFor(fatura => fatura.Itens).NotNull().WithMessage(Mensagem.ITENS_OBRIGATORIO);
           RuleFor(fatura => fatura.Itens).Must(list => list.Count == 0).WithMessage(Mensagem.ITENS_OBRIGATORIO);


       }
   }
public class ContratoItemDtoValidator : AbstractValidator<ContratoItemDto>
    {
        public ContratoItemDtoValidator()
        {
            RuleFor(item => item.CodigoItem).NotEmpty().NotNull().WithMessage(Mensagem.CODIGO_ITEM_OBRIGATORIO);
        }
    }

My startup class

    services
                .AddTransient<IValidator<FaturaDto>, FaturaDtoValidator>()
                .AddTransient<IValidator<ContratoItemDto>, ContratoItemDtoValidator>();

Meu controller (My controller)

 [Produces("application/json")]
    [Route("api/v1/")]
    public class HubController : Controller
    {

        [HttpPost("{fatura}")]
        [Route("faturamento")]
        public async Task<IActionResult> Faturamento([FromBody]FaturaDto fatura)
        {
            
            OrchestratorApp orc = new OrchestratorApp();
            return await orc.RedirectFaturamento(fatura);
        }
    }

And to trigger validation

 public async Task<JsonResult> RedirectFaturamento(FaturaDto fatura)
        {
          ...
            FaturaDtoValidator validator = new FaturaDtoValidator();
            ValidationResult results = validator.Validate(fatura);

codigo

My FaturaDto object came null and it is this test I would like to include but when the validation is triggered an error occurs "ArgumentNullException: Value can not be null. Parameter name: Can not pass null model to Validate."

erro

@JeremySkinner
Copy link
Member

JeremySkinner commented Jun 20, 2018

Hi there, please could you post your question in English?

Looking at the screenshot, you must provide a non-null root instance. This is by design.

@raffaelmiranda
Copy link
Author

raffaelmiranda commented Jun 20, 2018

Hi Jeremy thanks for answering, I'm using google translator

@raffaelmiranda
Copy link
Author

raffaelmiranda commented Jun 20, 2018

Is there a possibility, to include in the library to see this validation, when it comes to object null?

@raffaelmiranda raffaelmiranda closed this as completed Jun 20, 2018
@raffaelmiranda raffaelmiranda reopened this Jun 20, 2018
@JeremySkinner
Copy link
Member

JeremySkinner commented Jun 20, 2018

No, that's not possible I'm afraid - FluentValidation is designed to validate properties on a non-null object instance. You can't pass a null instance to Validate. You need to make sure that WebApi instantiates a valid instance before passing it to the validator.

@raffaelmiranda
Copy link
Author

raffaelmiranda commented Jun 20, 2018

Is this also true for an instantiated object that contains a null list?
This list should also be instantiated?

I can do something about it:
RuleFor(fatura => fatura.Itens).NotNull().WithMessage(Mensagem.ITENS_OBRIGATORIO);
RuleFor(fatura => fatura.Itens).Must(list => list.Count ==0).WithMessage(Mensagem.ITENS_OBRIGATORIO);

@JeremySkinner
Copy link
Member

JeremySkinner commented Jun 20, 2018

That's fine, the list can be null, but you should put a When condition on the second rule, like this:

RuleFor(fatura => fatura.Itens).NotNull().WithMessage(Mensagem.ITENS_OBRIGATORIO);
RuleFor(fatura => fatura.Itens).Must(list => list.Count ==0).WithMessage(Mensagem.ITENS_OBRIGATORIO).When(list => list != null);

@JeremySkinner
Copy link
Member

JeremySkinner commented Jun 20, 2018

Or you could combine them into a single rule and use the CascadeMode to stop the second rule from executing:

RuleFor(fatura => fatura.Itens)
  .Cascade(CascadeMode.StopOnFirstFailure)
  .NotNull().WithMessage(Mensagem.ITENS_OBRIGATORIO)
  .Must(list => list.Count ==0).WithMessage(Mensagem.ITENS_OBRIGATORIO);

@raffaelmiranda
Copy link
Author

raffaelmiranda commented Jun 20, 2018

I understood the explanation and thank you for your time.

@JeremySkinner
Copy link
Member

JeremySkinner commented Jun 20, 2018

You're welcome - let me know if you have any other questions.

@JeremySkinner JeremySkinner closed this as completed Jun 20, 2018
@lock lock bot locked and limited conversation to collaborators Aug 20, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@JeremySkinner @raffaelmiranda

Footer

© 2024 GitHub, Inc.

PHP网站源码坪地网站推广方案丹竹头企业网站设计永湖百姓网标王推广横岗阿里店铺运营东莞优秀网站设计南山seo网站推广惠州网站优化推广坑梓模板网站建设大运网站设计模板坪地关键词按天扣费广州建站福田网站seo优化东莞网站设计福永品牌网站设计大运英文网站建设坑梓百姓网标王推广双龙网站定制大鹏关键词按天计费深圳百姓网标王坪地网站开发坂田SEO按天扣费西乡百度竞价包年推广宝安推广网站双龙网络推广宝安百度网站优化荷坳营销型网站建设福永高端网站设计观澜关键词排名包年推广塘坑网页设计荷坳关键词排名歼20紧急升空逼退外机英媒称团队夜以继日筹划王妃复出草木蔓发 春山在望成都发生巨响 当地回应60岁老人炒菠菜未焯水致肾病恶化男子涉嫌走私被判11年却一天牢没坐劳斯莱斯右转逼停直行车网传落水者说“没让你救”系谣言广东通报13岁男孩性侵女童不予立案贵州小伙回应在美国卖三蹦子火了淀粉肠小王子日销售额涨超10倍有个姐真把千机伞做出来了近3万元金手镯仅含足金十克呼北高速交通事故已致14人死亡杨洋拄拐现身医院国产伟哥去年销售近13亿男子给前妻转账 现任妻子起诉要回新基金只募集到26元还是员工自购男孩疑遭霸凌 家长讨说法被踢出群充个话费竟沦为间接洗钱工具新的一天从800个哈欠开始单亲妈妈陷入热恋 14岁儿子报警#春分立蛋大挑战#中国投资客涌入日本东京买房两大学生合买彩票中奖一人不认账新加坡主帅:唯一目标击败中国队月嫂回应掌掴婴儿是在赶虫子19岁小伙救下5人后溺亡 多方发声清明节放假3天调休1天张家界的山上“长”满了韩国人?开封王婆为何火了主播靠辱骂母亲走红被批捕封号代拍被何赛飞拿着魔杖追着打阿根廷将发行1万与2万面值的纸币库克现身上海为江西彩礼“减负”的“试婚人”因自嘲式简历走红的教授更新简介殡仪馆花卉高于市场价3倍还重复用网友称在豆瓣酱里吃出老鼠头315晚会后胖东来又人满为患了网友建议重庆地铁不准乘客携带菜筐特朗普谈“凯特王妃P图照”罗斯否认插足凯特王妃婚姻青海通报栏杆断裂小学生跌落住进ICU恒大被罚41.75亿到底怎么缴湖南一县政协主席疑涉刑案被控制茶百道就改标签日期致歉王树国3次鞠躬告别西交大师生张立群任西安交通大学校长杨倩无缘巴黎奥运

PHP网站源码 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化