Fluent Validation in C# - The Powerful Yet Easy Data Validation Tool

Поделиться
HTML-код
  • Опубликовано: 28 сен 2024

Комментарии • 283

  • @steejayk
    @steejayk 5 лет назад +11

    My favorite youtube programming channel.

  • @Francisco-Gutierrez
    @Francisco-Gutierrez 5 лет назад +5

    Guys, I think Tim deserves so much support on patreon, he is an amazing teacher. Thanks Tim!!

  • @sugamsingh5213
    @sugamsingh5213 7 месяцев назад +4

    Wow!! I wasted a whole day looking for ways to validate. Your explanation is so easy to understand and Thank you so much for this video :)

  • @behi667
    @behi667 5 лет назад +1

    This is freaking awesome. I literally just finished writing my validator, where a single fuction is over 100 lines... But this... this... omnomnom. Thank you!

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      I'm glad you enjoyed the video.

  • @DrWambua
    @DrWambua 3 года назад +1

    This is a lesson I've overlooked over and over and guess what, I am actually redoing validation in my Application albeit a year after deployment! Well, Thank you Tim!

  • @devoiddude
    @devoiddude Год назад +3

    This fantastic stuff, really made me rethink how I do validation, I was just using if statments every where, this is much better, thank you sir!

  • @acidhauss7018
    @acidhauss7018 5 лет назад

    Great video again.
    Picked up the SQLite database course and about 1/4 way through. Highly recommend it to anyone seriously learning C# in their free time, with a bit of cash to spare.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      Thanks for the recommendation! I'm glad you are enjoying it.

  • @CRBarchager
    @CRBarchager 5 лет назад +2

    Upwoting this video before I see it since I know it will be good.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      :-) I'm glad you have confidence in me. I hope I never disappoint.

  • @LuigiZambetti
    @LuigiZambetti 5 лет назад +1

    Also in this week I've learned something new. Thank you Tim.

  • @karendoran3692
    @karendoran3692 5 лет назад +2

    Hey Tim this was another awesome video and have learned a lot of great concepts and tools from you. Would you please be able to do a tutorial on how to create reports in a C# application? Maybe using visual studio report writer or a third party nugget package. I have not seen any good information on creating reports in visual studio.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      It is on the list. Thanks for the suggestion.

  • @saturdayscience5540
    @saturdayscience5540 5 лет назад

    An excellent extension homework to your SQLite Application from start to finish course. My thoughts had been thinking about robust data validation and along comes this tutorial. Thanks for the great video.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      You are most welcome. Thanks for watching.

  • @scotolivera8207
    @scotolivera8207 3 года назад +2

    Thank you, just what i was looking for

  • @senaszel
    @senaszel 4 года назад

    Awesome presentation.
    It's been a year since it has been posted. During that time library went up to 26m downloads on NuGet. No surprice.
    I've spend 8h yeasterday validating inputs from winforms and it still was short on elegance of FluentValidator. With knowledge passed in this vid similar efect could be achived in half an hour! Just toss in some KeyDown disallowments and its good. This is amazing.

  • @vinuhosanagar1
    @vinuhosanagar1 5 лет назад +2

    Thanks Tim for super video. What do you suggest for those of us who can't use or not allowed to use such 3rd party tools at workplace. This works for our hobby projects.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +3

      You have a couple options, depending on your environment. First, this is open source code. You could download the actual source and include it in your application. Second, you could discuss with your manager the definition of "3rd party tools". It makes (some) sense not to rely on something that is paid or that is a black box because you are responsible for your data. It makes little sense to draw an arbitrary line of which code is ok when you have access to all of it. Technically, you could re-type the Fluent Validation library (or Dapper) code into your code and now it isn't 3rd party anymore. I would pitch it as you outsourced a portion of your code and, while you control it and have full access to it, someone else is doing the work for you on it. Finally, if those arguments don't work, I would approach it from the time perspective. You can absolutely recreate the wheel in your code. Do it all yourselves. However, that is inefficient and less secure since these critical libraries have hundreds of thousands of people looking at them and reviewing them. What is the likelihood of you writing better, safer code?
      In the end, if they don't budge, you are stuck with Data Annotations (not a bad option if you control the models) and/or writing your own validation library code.

  • @rimmongeorge3587
    @rimmongeorge3587 5 лет назад +5

    Thanks Tim, you are really talented, not only in programming but also in explaining it.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      I appreciate the kind words.

  • @FinalProgeny
    @FinalProgeny 5 лет назад +1

    I'm currently working on validation for something I'm doing, but came upon the conundrum which I didn't see you address. In the case of non-string fields in a Model, such as DateTime, Double etc; if, in your example 'Ten' is input into Age instead of '10', if I set the value of Person.Age = Ten, it will raise an exception. The way to address this is to TryParse the value as you have done. But in my case where there are 6 DateTimes and 2 Integers and 1 Double, that's a lot of work to do before I can even set properties of a Model, before I can then validate it. All those steps seem like validation to me, which in my mind disjoints it from a Validator class, if it's necessary to parse multiple values, just to input it to a model, to then perform additional validation.
    This is what I would have liked to have done, but did not want validation outside of any Validator classes that I created. So therefore I just have a static class with a method per property which performs the validation. I call each validator method independently, which in turn will return the property name if it fails validation.
    What are your thoughts?

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      Excellent question. I actually wrestled with addressing this or not in the video. I finally decided it was a rabbit hole I didn't want to go down (I try to avoid 2+ hour videos). How you address this situation is one that really depends on your environment and your situation. However, remember that the model is simply a tool to hold data. You can (and probably will) have different models for data coming from the form vs. data coming from the database, even if it pertains to the same area. In this case, I would probably add a property for AccountBalance (the issue in my form) called AccountBalanceText. The setter would store the value but also convert it to decimal and store the resulting value in AccountBalance. Then, I could write a validator against the AccountBalanceText that ensured it was a valid number in string format and I could write a validator against AccountBalance that ensured the value was in the correct range. I might make it a dependent validator, since if the text value is not valid, the decimal version won't be either. The result would be validation in one place that is consistent.

    • @FinalProgeny
      @FinalProgeny 5 лет назад +1

      @@IAmTimCorey That's a great idea. I'll look into this. The other benefit, as demonstrated in your video is, you now have a populated and valid object ready to be used, rather than passing all the form fields to a validator, to then create an object using the same methodology. This is also something that I had wanted. Thanks for you help!

  • @ashishjain871
    @ashishjain871 5 лет назад

    Thanks for the video. Clear, easy to follow and helpful :).

  • @MrMrkBo
    @MrMrkBo 5 лет назад +1

    Lol...(sigh) "this is demo code, I wouldn't necessarily put all this in my button click event. "
    Hey Tim...guess where I put all my code related to my button click event? Haha, I still like my C# program... I just wouldn't want you to see it haha!
    Also, guess what all of my data validation consists of? Yep, you guessed it...try - catch blocks lol.
    Thanks for giving me the direction I need to improve and for another great video!
    Mark Botirius

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +2

      That's pretty common but now that you know a better way, it is good to see you moving that direction. We don't start out as perfect programmers; we only get there through hard work and change over time.

  • @grantsamson2384
    @grantsamson2384 4 года назад +1

    Was following along, and made a second library (to represent that I can't access the model library) where I imported the package. I overloaded the Validate() function in my PersonValidator with a new Validate() where I take in a PersonModel, call the parent Validate function and return a custom return type CleanValidationResult, which is just a bool and list (which is all the GUI cares about anyway). When I tried to call it in the dashboard, I was getting an error of "The type 'AbstractValidator' is defined in an assembly that is not referenced."
    My question is, if I'm referencing a function in PersonValidator class (which I can access through the library reference), passing in a PersonModel, and getting back a CleanValidationResult (which I can also access through my library), why would I get an AbstractValidator error at all? The library has the package, and the library function uses it, in theory the GUI shouldn't know or care about the AbstractValidator type, because it's only referencing things through the classes which I have access to through the function call.

    • @grantsamson2384
      @grantsamson2384 4 года назад +1

      Ok, I still don't know why I got the error, but I found a workaround; I created a class PersonValidationHolder, which has a PersonValidator object, and put Validate as a passthrough function in the PersonValidationHolder. I make a PersonValidationHolder in the Gui and call the Validate() function in that, which seems to work just fine.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +1

      I'm not really following but I'm glad you figured out how to get it to work.

  • @lengsokpheakdey
    @lengsokpheakdey 5 лет назад

    Very great and useful tutorial Thanks Tim.

  • @rennishj
    @rennishj 4 года назад

    Thanks for this great video Tim.

  • @daizwap9454
    @daizwap9454 4 года назад

    amazing episode thank you Tim Corey

  • @gochadarjania170
    @gochadarjania170 2 года назад +1

    Thanks for this video!

  • @webbi1540
    @webbi1540 5 лет назад

    Great video master Tim

  • @michalisp1121
    @michalisp1121 4 года назад

    Well explained, Tim! Just one detail that made me curious. I was wondering how come the failure error displayed "First Name"... when you put the {PropertyName} which was "FirstName". I was amazed to find out that FluentValidator automatically adds a space after an upper-case character and so the property name can be split into words. Also smart enough that when I tried "FirstNameOfMVP" it converted it into "First Name of MVP" :)

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      That is pretty cool. They baked some nice features into the product.

  • @sweetsazd11
    @sweetsazd11 4 года назад

    Great explanation! Thank you :)

  • @movsar42
    @movsar42 3 года назад

    This is so useful! Thank you!

  • @nickbarton3191
    @nickbarton3191 5 лет назад

    Didn't know about Fluid Validation, thanks.
    Small point but I hope that we aren't putting returns in the middle of blocks in our production code. There should be a single return only at the end of a function. Very hard to spot returns during maintenance otherwise, and can lead to confusion and less productivity.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      Well, I'm going to disagree with you here. Code is meant to be read by humans. If a line of code is so long you have to scroll horizontally to see it all, it isn't readable. Line returns read just fine as long as you follow the indenting best practices (which Visual Studio enforces in most cases) of indenting connected parts of the line one more indent than the parent. That way you know that the following lines are under the parent (just like you know that code is associated with an if statement because it is indented under the if.

    • @nickbarton3191
      @nickbarton3191 5 лет назад

      Sorry but I think you missed my point. Nothing to do with the length of a line of code.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      Oh, gotcha. You are saying that you prefer one "return output" statement at the end vs. "return true" in one spot and "return false" in another, not carriage returns in our code. OK, I'm with you now. Yeah, I mostly put just one return in code but there are exceptions. This would be one of them in a typical environment. If you look at the button click event, we identify an issue that stops us from proceeding. Instead of creating one big if/else statement and wrapping all of our code, I just check for the issue (invalid text in the Account Balance field) and I exit out of the method early. It keeps my code cleaner and reduces the nesting of if statements. But typically you are correct, it is better to have just one return at the end.

    • @nickbarton3191
      @nickbarton3191 5 лет назад

      On a big project, creating an exceptional circumstance in the coding guidelines means that coders tend to abuse it. Hard keeping 20 programmers in order 😁

    • @nickbarton3191
      @nickbarton3191 5 лет назад

      Tim, I'm enjoying your series. Maybe it's a little slow for me but I can understand that you're teaching.
      One topic that I love to see an explanation of is Currying. I've done it in Javascript by following someone else's template but never really got to grips with it. Can it be done in C# ? The Javascript I did needed pointers so perhaps not.
      Would value a video on this.

  • @janicebridle8014
    @janicebridle8014 2 года назад

    Is there a way to define the alignment of the data validation memo...the leftmost column ends up cutting off half the memo box

  • @LuigiZambetti
    @LuigiZambetti 5 лет назад

    Hi Tim, have you in plan to make a future video about WCF? (that is still used in enterprise applications).

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      It is on the list but it keeps getting pushed down by higher priorities.

  • @milanmladenovic
    @milanmladenovic 5 лет назад

    Great video. Thanks a lot!

  • @Saleh-le2zf
    @Saleh-le2zf 3 года назад +1

    THANK YOU!

  • @guilhermegoncalves6529
    @guilhermegoncalves6529 4 года назад

    Great! Thank you Tim :)

  • @MohammedIbrahim-hk2bp
    @MohammedIbrahim-hk2bp 3 года назад

    Why I have to instance model if the flunt library extends it

  • @khoadoo5505
    @khoadoo5505 3 года назад

    Hi Tim,
    Is there a way that I can reuse validation from PersonModel to CreatePersonModel without checking field ID?

  • @darrellrobertparker5401
    @darrellrobertparker5401 3 года назад

    Great Course thanks! Do you do personal trainings as well?

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      Thanks and no, I do not. I don’t have time to do personal training anymore.

    • @darrellrobertparker5401
      @darrellrobertparker5401 3 года назад

      @@IAmTimCorey Bummer, appreciate the reply. Good Luck.

  • @MrBrouilles
    @MrBrouilles 3 года назад

    Thanks, useful! Not possible to show the error in real-time under the associated TextBox? More user-friendly.

  • @hom-sha-bom
    @hom-sha-bom 2 года назад +1

    Can you do conditional rules like first name and last name both can be empty, but if last name is not empty then first name cannot be empty

  • @Santino404
    @Santino404 5 лет назад

    Tim, can you show how to access the UI thread to update list boxes from other classes, please? It's something that has always bothered me. Many thanks

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      Other classes have access to the UI thread because they are on the main thread. It is only if they are used in other threads that it becomes a problem. I'll probably cover this in a future video.

  • @PapLabros
    @PapLabros 5 лет назад

    Could you please make a video about application localization?

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      That is on the list. Thanks for the suggestion.

  • @AshrafSada
    @AshrafSada 4 года назад

    Thanks Tim

  • @alaamohammed3491
    @alaamohammed3491 Год назад

    if I did have the same rule for multiple proprieties (with only different parameters like max Length), Is there a way I could make a delegate or any think like this that could point at the same rule. And use it with different proprieties and there corresponding parameters.
    As it will be easier to make everything consistent, in case I wanted to change anything in the rule itself. Specially, that I have many Models and Dto that use the same rule.
    Thanks.

  • @carlosjunior5371
    @carlosjunior5371 5 лет назад

    Hello, congratulations on the work. To make a code more testable, I have as a practice to test even my value objects. In one scenario, assuming an aggregate is composed of VOs and their validable primitive properties, how do I merge these validations into aggregate validation?

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      You can do something like this: stackoverflow.com/questions/21115179/fluentvalidation-check-if-one-of-two-fields-are-empty

  • @TheChukso
    @TheChukso 2 года назад

    is it possible to use dependency injection as it was a normal class? I mean I have a couple of entities to inject, should I use dependency injection as always?

  • @dheerajambippi2283
    @dheerajambippi2283 3 года назад

    hi Tim, this was great video but i was searching on data Sanitization in .net core 3.1 like sql injection and Html tags. plz help me

  • @fj8551
    @fj8551 7 месяцев назад

    I want to get the response of validations in xml format, can someone help me please?

  • @DamianWalczak
    @DamianWalczak 5 лет назад +1

    "in this episode Im going to introduce You to yet another third party nugget/dependency which you will have to rely on...." some of your videos are bit misleading, perhaps it might by worth creating new playlist "3rd party nuggets" ?
    Great work anyway! :D

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      I would do that with any closed-source library. However, with open source libraries where you could put the raw source code for this tool into your application, I don't see it as quite the same but I take your point. I'll see what I can do.
      Just to address the overall thinking, everything we do in development is based upon external dependencies. We rely on Microsoft for a TON of them (Console.WriteLine is third-party (to us) code). We can do it all ourselves (if we take what Microsoft gives us as permitted and not counted) but that introduces it's own problems. For instance, I would not implement my own authentication system because I am only one person. If I miss a security flaw, my system is now vulnerable. If I fail to optimize a certain area, my system is now slower. These are the benefits that "third-party" code provides. You get extensive testing (9.3 million downloads means a lot of people have tried a lot of scenarios against this code - we can't say the same for our self-written code) and you get a team of very smart developers working to make the system as efficient and secure as possible. Will there be mistakes? Absolutely. Will the number of mistakes in their code be greater than in the code that I would write to replace this functionality? Almost definitely not.
      On the other hand, if we rely on a tool that goes away, we may have a problem in our code. I get that. I also get that we don't control what the third party tool decides to do. I depended on well-known tool that introduced breaking changes to a version. Those breaking changes eliminated what I was using the tool for (it was integral to my entire application). However, because it was a NuGet package, I could freeze the version at the last version before the breaking change. Then I worked to replace that functionality in my code. If I really felt passionately about it, I could have forked the code and maintained my "better" version from there. That's why I don't worry overly much about open source third-party libraries.
      At the end of the day, I try to do the work that only I can do and outsource the rest. If I can eliminate weeks of development work by replacing my code with a library, I will consider it. It isn't a given, since I have to weigh the risk vs. reward (on both sides). However, it gives me options that I refuse to just blanket eliminate because of a label that is applied equally to unequal situations (open-source vs closed source, community support, longevity, etc.) Also, if I write my code correctly, I can limit my liability. For instance, if Dapper were to go away and I couldn't use their source code for some reason, that would not be the end of the world. I write my applications in a way that the only Dapper-specific code is in one or two places. I could replace those couple methods with ADO.NET in a couple hours (including the time to get the mapping working correctly).

    • @DamianWalczak
      @DamianWalczak 5 лет назад

      ​@@IAmTimCorey ​Thanks for getting back to me and I completely get where You're coming from...
      tools like log4net, fluent validation caliburn micro etc exist for a reason.
      Recently I was looking for a CSV parser and sure I could write my own or I could import one from Microsoft Visual Basic library which has been tested 100000x times
      However my mind works in a different way I NEED to know how things work before I start using them,
      I will F12 and get to the source of function so I can understand it completly same as cars or electronic devices best way to learn it is to take it apart :)
      I can definitely see the use of nuggets/tools/etc just wouldnt recommend them to completely new developer.
      IE. before you go and start playing with MVVM framework of your choice do it by hand first, understand RelayCommand. Property Changed Events, Can Execute etc..
      then you can jump in and make your life easier with MVVM lite or other framework.
      I also agree in regards of safeguarding your own code so even if library which you're using would go away refactoring your code to make it work again wouldnt take long (Im big Fody -> property changed and Validar fan)
      Good Luck!

  • @ZoidbergForPresident
    @ZoidbergForPresident 5 лет назад

    When you do .Cascade().with().withmessage.with. etc I wonder how the system knows which you are adding when... I mean, each of those returns a validator then? I mean the withmessage is linked to the correct rule...
    Bah I guess it's related to how the framework is built but I'm wondering as some pretty strange behaviour may be implemented...

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      The output of one method is used as the input of the next method. That is how it knows the order.

  • @DavidMartin-vs1dm
    @DavidMartin-vs1dm 2 года назад

    Is this related to Blazored.FluentValidation (from Chris Sainty)?

  • @phamthehung2
    @phamthehung2 2 года назад

    Can fluent validation be used with WPF data binding?

  • @erictenwestenend868
    @erictenwestenend868 2 года назад

    How to set focus to the first invalid element?

  • @kanijari
    @kanijari 4 года назад

    Hi tim. Goes without saying, great videos! Im creating a backend api in asp.net core that will talk with an angular frontend. Is it a good idea to implement custom async validation in the api? What sort of benefits and/or drawbacks could it have?

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +1

      You always want to have validation in the API because you can't trust the front-end. There is nothing limiting the person to using Angular as the front-end. They could go to Postman and call your API directly. Even if you limited access to your API to only the front-end server using a firewall, that doesn't mean that the Angular developers six months from now will remember to properly validate their inputs.

  • @fatimaajij428
    @fatimaajij428 5 лет назад

    Hi Tim Would you please make some tutorials on SALT SHA-256 for Password Protection and the one you follow format for password protection please

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      I can add it to the list but my overall recommendation is to not roll your own authentication. Use a pre-built one. Otherwise, you endanger your application.

    • @fatimaajij428
      @fatimaajij428 5 лет назад

      oh , which one do you think is better to implement?
      @@IAmTimCorey

  • @serhiihorun6298
    @serhiihorun6298 4 года назад

    Thank you! Дякую!

  • @Francisco-Gutierrez
    @Francisco-Gutierrez 4 года назад

    What about Data Annotations, do you prefer one over the other? Thanks

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +2

      These are more powerful but they take more setup work. I typically stick with data annotations until I need more power.

    • @menendeze
      @menendeze 4 года назад

      This is all about that package, this is so basic, and everything explained here can be achieved with Data Annotations and more, with the posibility that use them later on a web project without changing anything. Data Annotations have a Validator that you can use on Windows Forms. Probably he is going to make a video of what are the powerfull options this package have.

  • @FoHsi
    @FoHsi 4 года назад

    Why and how {PropertyName} display "First Name" instead of "FirstName"?

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +1

      Because one of the attributes we applied was to rename the property for display purposes.

  • @ore_bear8045
    @ore_bear8045 3 года назад

    I downloaded the startcode, but it has no dependencies so I can't add reference and download the fluent. Anybody have experienced the same?

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      Not sure what the issue is. Is the project still a .NET Framework project or did it somehow get converted to .NET Core?

    • @ore_bear8045
      @ore_bear8045 3 года назад

      @@IAmTimCorey Thanks for your answer, I´m not sure how to tell but looking in the dashboardUI.csproj, v4.7.2

  • @torrvic1156
    @torrvic1156 2 месяца назад

    Thanks a lot! It seems like this exactly what I need in my current situation. Is it possible to inject data from outside of Validator class? I think it should be possible and if it is then it is a serious advantage over ordinary DataAnnotations decorators.

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +1

      Yes, you can do that. Just be careful not to make a really messy validator.

  • @javadjannesari9734
    @javadjannesari9734 2 года назад +1

    gooood

  • @brianviktor8212
    @brianviktor8212 3 года назад +1

    Just a little off-topic hint: When you do: "if (condition) return true; else return false;"
    You can simply do instead: "return condition;"

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +5

      Yep. I usually point that out. The if statement is just a bit more readable for new developers, though.

  • @bastedboyderzthine
    @bastedboyderzthine 5 лет назад +1

    Please don't use a demo project. How can we learn how real-world project looks like and how they are organized?

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      I can't do real-world projects in order to show how to use one specific item. It just takes too much time. My Tournament Tracker application took 25 hours of video to show a real-world application and really, it could have been a lot more (I didn't include a lot of items like source control, a build system, unit tests, and more). Real-world applications are important, and I create my courses (which can be a lot longer) as real-world applications usually. However, when I am going to focus in on teaching one specific item, I use a demo application. There just isn't a way around it.

  • @gpzim981
    @gpzim981 3 года назад +2

    The problem with Fluent Validation is that it is only useful on the UI layer to make sure UI doesn't break the contract of the Application layer. Outside of UI layer this sort of validation belongs to the domain layer which should not have a dependency on any external resources.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      You can use the same model through much, if not all of your application. The model has no dependencies on Fluent Validation. That means you can run this validation on your models that you get from the database if you want as part of your business logic.

  • @neralem
    @neralem 3 года назад +2

    So you say if I'm a vampire I can't use your software because I can't enter my date of birth?! Thats not okay! And time travelers also can not??

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +5

      Correct. I am very exclusive with who can use my applications.

  • @RalfsBalodis
    @RalfsBalodis 4 года назад +1

    0:00 - Intro
    1:00 - Demo application walk-through
    2:56 - User input validation
    6:04 - Where to put data validation
    7:07 - Fluent Validation: adding a reference
    9:19 - Implementing Fluent Validation
    18:23 - More rules for validation: String length
    20:00 - Validation custom error messages
    22:28 - Cascading validation errors
    23:29 - Input validation: allowed characters
    28:44 - Fluent Validation built in variable names: updating error messages
    34:08 - CascadeMode scope
    35:49 - DateTime validation
    40:41 - Recap and concluding remarks

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +1

      Thanks! I added it to the description.

  • @shinrafahell
    @shinrafahell 3 года назад +2

    I think it would be better to have the error message popping up as a tooltip inside the field.

  • @rashidselemani475
    @rashidselemani475 2 года назад +2

    I don’t have comments, I’m speechless Sir!!!

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +1

      I'm glad it was valuable to you.

  • @pierreplourde
    @pierreplourde 2 года назад +2

    This one is worth the price of admission!! Great video and good information.

  • @menendeze
    @menendeze 4 года назад +1

    It's a very understandable video, but this is all about the package FluentValidation. For your next video please explain about DataAnnotations, all of this you can do it with DataAnnotations and use a validator, then you can make a foreach and with an errorprovider set the error for each control and you can use the same class on a web project without modifications.
    I’d like to learn more about DataAnnotations, thank you for your videos.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +2

      Fluent Validation was the focus of this video. As for Data Annotation, no, it can't do everything that Fluent Validation can do but I can add that as a suggestion for a video.

  • @BlackFire69
    @BlackFire69 4 года назад +1

    Amazing tutorial. I've just recently discovered this package and couldn't find anywhere, where someone was explaining exactly how to use this package. Awesome. Thank you!

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      You are most welcome. Thanks for watching.

  • @laughandtune
    @laughandtune 2 года назад +1

    Can we pass a list of errors in the message?

  • @ganeshb7893
    @ganeshb7893 2 года назад +1

    Fluent validation is very useful I have used it in my project as server-side validation. Thank you Tim for
    most valuable content and learning video .

  • @alihsanelmas
    @alihsanelmas 3 года назад +1

    Thanks for this great video! But the link for source code on one drive is not valid anymore. Can you share it again? Thanks.

    • @tomthelestaff-iamtimcorey7597
      @tomthelestaff-iamtimcorey7597 3 года назад

      Bad news, when we changed storage providers, se lost several source files for older videos, this being one of them. I will update the notes with this change. Sorry about that.

    • @alihsanelmas
      @alihsanelmas 3 года назад

      @@tomthelestaff-iamtimcorey7597 Too bad :/ Anyways, thanks for letting us know

  • @kojoig
    @kojoig 5 лет назад +1

    Thank you for this amazing video.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      You are most welcome. Thanks for watching.

  • @GregWilliamBryant
    @GregWilliamBryant 3 года назад +1

    Hi Tim, I love your videos, but it would be lovely to have Advance Fastrack version of these videos for reference.

    • @tomthelestaff-iamtimcorey7597
      @tomthelestaff-iamtimcorey7597 3 года назад +1

      For several of his RUclips series, Tim has more concise versions available for sale at IAmTimCorey.com. The paid versions often have additional content also.

    • @GregWilliamBryant
      @GregWilliamBryant 3 года назад

      @@tomthelestaff-iamtimcorey7597 AHH ok. I will keep that in mind, I do feel that my learning resources are spread among a number or sources, which is primarily the reason I've not dipped into his courses.

  • @wa1gon
    @wa1gon 3 года назад +1

    Great video. It would be nice to have one using Blazor.

  • @Chivasque
    @Chivasque 3 года назад +1

    Thanks Tim, you are amazing !

  • @bensonputhethu5918
    @bensonputhethu5918 3 года назад +1

    Sir, could you please show how to use fluent api in an MVC form?

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +2

      Topic suggestion noted and added to my list, thanks.

    • @bensonputhethu5918
      @bensonputhethu5918 3 года назад

      @@IAmTimCorey thank you so much sir!

  • @WaahaidIWKY
    @WaahaidIWKY 3 года назад

    I do not understand the point of this though as this only would work for text or string data, if I want to validate numbers or non-nullable fields I have to validate them beforehand like an int value cannot be null or will not accept letters, and I have to d that for every non-nullable field

  • @prateekbhardwaj9943
    @prateekbhardwaj9943 4 года назад +1

    I thought you are Mosh :(

  • @andreirosu3450
    @andreirosu3450 3 года назад

    Hi Tim,
    I have some struggles validating a BindableCollection . Is that even possible with FluentValidation?
    What I mean is:
    - I have a DataGrid binded to a BindableCollection
    - Inside my model i have a string property (which will be binded to a DataGridTextColumn)
    What I would like to achieve is to validate that column for duplicates entries.
    I have a hard time with it.
    Any tips?
    Thanks in advance!

  • @niangel2704
    @niangel2704 3 года назад

    Hi Tim and congrats for this yet another one very useful tutorial.
    My question is: I added the FluentValidation lib into my models project using nuget but then in the main project code it seems like it cannot find the .Validate function of the abstract class although the Models project is referenced into the main project!! It suggests me to install FluentValidation into the main project as well!! Is it what I am supposed to do? To insert the nuget FluentValidation lib both in the models project and the main project as well? Thanx again for your excellent tutorials!!

  • @bowlesed1
    @bowlesed1 5 лет назад +1

    Tim, I have found that having three edit levels works very well for me. One is a mechanical edit level, one is a logical edit level and the third is an edit related to a specific type of data. A mechanical edit ensures numeric fields contain numbers. Alpha fields contain any characters. The next level for data validation is to check for logical values. The first name must contain at least 1 character, the last name must contain at least 1 character, the City must contain at least 1 character, the State abbr must be 2 characters and in the standard list of State abbreviations, and the Zip Code must be 5, 9 or 10 digits if U.S. or 6 alpha-numeric characters if Canadian. Other fields may have minimum and maximum lengths (0, 30) like an address. All of the edits, both mechanical and logical can be included in the same class that can be shared between all web applications that handle input data. The logical edits can access data tables, etc. to validate different inputs.

  • @hamouz718
    @hamouz718 4 года назад +1

    Will this work for WPF?

  • @Istvan_01234
    @Istvan_01234 3 года назад

    "Never trust the user!" Made my day :D
    ruclips.net/video/Zh1ccvTFzs8/видео.html
    Btw thanks, great video!

  • @bahrian4394
    @bahrian4394 2 года назад +1

    This is a great video done sir

  • @dsmyify
    @dsmyify 5 лет назад +1

    Little Bobby Tables.

  • @RalfsBalodis
    @RalfsBalodis 4 года назад

    Awesome tool!
    I was hoping for DIY wothout nugets tho, but I guess why make life more difficult than you have to.
    I noticed that you don't have to pass in arguments (string nor date time) in the private methods when you called them. Neat.
    With messages I expected string interpolation. I don't know why, but it feels like that would be more consistent with writing C# in general. I guess there was a good reason to make it this way?
    I wanted to create text input field in wpf application, that would accept only numbers. Wasn't able to find how. At-least not straight forward way. I think I could do it with preview event tho while trying something with Char.IsDigit... Thanks for the hint ;)
    Anyway. I had to validate that input if it could be parsed to number (int in my case).
    My approach was to surround that method with try catch. If it failed, catch would update that field with default value and value would be used later. It was ok in my case, but I can see how it would not be ok in other cases. Pretty terrible... :D

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      We use the curly braces instead of string interpolation because we are pulling these items out and replacing them using the validation system, not just C#. We don't have the data at design time (PropertyName becomes whatever property it is, for example).

  • @alin9008
    @alin9008 5 лет назад +1

    Thanks Tim, awesome Video!
    I was wondering if we're violating the DRY principle in the FirstName and LastName validation code, since it's exactly the same code.
    Would it be possible to extract the two repeated checks as their own methods?
    Thanks

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +2

      It is possible. However, you need to be careful since you might want to validate just a bit differently down the road.

  • @lastidea4925
    @lastidea4925 2 года назад

    TotalLength doesn't work and I don't know why there is no solution

  • @DodgerDude74
    @DodgerDude74 3 года назад

    A+++++ Thanks! Great video to get a person started; especially the last segment where you give the idea of creating all of your custom validation rules that return true/false and putting them in a local Nuget package to share.

  • @chezchezchezchez
    @chezchezchezchez 5 лет назад

    Cool.
    So if you have a winforms with say 30 text boxes, do you use this "Fluent Validation" for ALL of them?

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      Let's reword this: "Which fields will the user potentially put bad data into?" If the user can enter values in 30 fields, all 30 should be checked for correct/valid data. Now some fields might not require validation (checkboxes that can have either state, dropdowns that have the first value auto-selected, etc.) so you could technically not count these in your 30. In general though, you need to check all data that comes from the user.

  • @salmanalikhan8290
    @salmanalikhan8290 3 года назад +1

    Best teacher....

    • @IAmTimCorey
      @IAmTimCorey  3 года назад

      Thanks!

    • @salmanalikhan8290
      @salmanalikhan8290 3 года назад

      @@IAmTimCorey respected sir, please make a video on getting data from tables having many to many relationship. Also please give time to elaborate how to deploy mvc web project for hosting. Thanks for your hearted response

  • @Layarion
    @Layarion 4 года назад

    Tim, I'm building a ConsoleUI app on .net core and .net standard libraries.
    I'd like my logic or model layers to do validation *and* color code keywords in the error message that bubbles up from exceptions.
    So I used a list that builds a ValueTuple of string and color enum. Then the ConsoleUI loops over the list in a writeLine method. Is this fine?

    • @IAmTimCorey
      @IAmTimCorey  4 года назад +2

      If it works in your situation, then you've passed the most important hurdle. However, in most situations you would not want to assign the color in the logic layer (models aren't a layer in themselves so I'm assuming you mean business logic for them as well). Instead, that is typically a choice for the UI since the UI might do things differently. Instead, you would assign categories to the messages (info, warning, error, etc.) and then in the UI you could color code appropriately. That way you could display them in another way in another UI. Right now, though, you basically have one layer in two different places. When you have things like the color of the UI in the business logic layer, you actually are tying the two layers together into one. That can be ok, just note that is what is happening.

  • @rodrigo6459
    @rodrigo6459 5 лет назад

    Hey Tim!.. great tutorial!... but i need a quick help here, is there a way to tell which TextBox was the responsible for the error?, the idea will be to change the background color for the field that generated to error to something like red.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      You know which property in the model is in violation. This isn't really a WinForm-specific tutorial so I didn't get into that but you can assign the messages back to the fields in reverse of how you put them into the model. So, if the FirstName property is a problem, you apply that to the firstNameText property on the form. At first it will be a manual process but you can wire it up to be automatic with a little ingenuity.

  • @Mrnik123s
    @Mrnik123s 4 года назад

    Hi Tim,
    Nice explanation !!! Although, I have one question what if there are validations that require hit to a DB for e.g."XYZ property value already exists in db". Does it then make sense to add a dependency of persistence layer in validator class? I think it will make a more coupled solution unlike we wanted to separate the domain logic from validators.

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      It depends on your situation but typically I would make that a separate thing from the validation. It is still a validation but it would be a carefully executed check (so it doesn't run every time they hit a key in that field - maybe wait until they tab out, run it async, etc.)

  • @erinmclaughlin9581
    @erinmclaughlin9581 4 года назад

    So in this example you're asking for all of the information at the same time. How would you handle validation if you had this broken up into steps -- for example, in "Step 1" you ask for the first and last name and then in "Step 2" you ask for the Account Balance and Date of Birth. If you wanted to validate at the end of each step, would it be better to create multiple validators for that one model, or should you break the model up into multiple models representing each step? Thanks!

    • @IAmTimCorey
      @IAmTimCorey  4 года назад

      You would probably break the model up into models per form.

  • @glutz2
    @glutz2 5 лет назад

    Hi Tim. Firstly, I wanted to thank you for all the hard work you put into your channel; it's one of my favorite c# resources. Secondly, I was hoping you could point me in the right direction for my current project regarding validation. I'm using a DataGrid to show a collection of "subjects" and each subject (row) has a start and end range. I want to return an error if one row has a range that overlaps with another rows range. Presently, I have this working using custom row validation rules that checks everyone for overlap after that row is edited. However, I can't find (I've googled extensively) a clean way to re-validate every row that could potentially be affected by changing one row's start or end range. My current solution is just refreshing my BindableCollection after every edit but that seems hacky and gives a poor user experience because you lose cell focus. So I'm thinking instead I should create custom validation inside my subject model so I can control when subjects are re-validated? But, I saw that you have been helping your viewers in the comments so I thought I'd ask your opinion. Thanks in advance for your help!

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      I think you are on the right track. A custom validator is probably your best option.

  • @sidieudelphin1685
    @sidieudelphin1685 5 лет назад

    Hi Tim, That is a great video. I was wondering if it is possible to createa Custom textBox that has several bool property for example and when ever one of these property is true it checks if the texbox is valid, and there would be a Validate textBox Class that would have several methods that would relate with each one of the properties, and you would have a method to check if the textbox is empty,1 to check if it only numbers,1 to check if there is special charcter, That way you would have one class that do the job you would not have to create one validating class for each model. Also How can I use Fluent Validation with error provider instead of a listbox please. Thanks for the Knowledge.

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад

      That would be some extra work but I think it could be done.

  • @krzysztofwozniczak4747
    @krzysztofwozniczak4747 5 лет назад

    Tim i think is bug in your code. I think in if function you don't have return so only one valid of 'Account Balnace' really works.
    I think this is correct:
    if (results.IsValid == false)
    {
    foreach (ValidationFailure failure in results.Errors)
    {
    errors.Add(failure.ErrorMessage);
    return;
    }
    }

    • @IAmTimCorey
      @IAmTimCorey  5 лет назад +1

      I assume you mean at 16:59 and no, that wouldn't really work. The reason why is that as soon as you hit a return statement, the execution is complete. It won't do anything else. Instead, I want to add each error to the list before I'm done. I don't need a return statement. I add all of the errors and then the method finishes. If you are saying that we should return before displaying the "Operation Complete" messagebox, I decided to leave that in since we were just simulating and I wanted a clear "we are done" indicator. However, we would need to do it outside of the foreach after it has concluded.

  • @ilyubenok907650
    @ilyubenok907650 3 года назад

    Any idea how to integrate validation for a combobox? I am trying to set the code so there has to be a selection from the combobox to pass validation