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

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ก.ค. 2024
  • Full courses: www.iamtimcorey.com/
    Patreon: / iamtimcorey
    Newsletter signup: signup.iamtimcorey.com/
    Data validation is extremely important. The problem is that it can create a lot of excess code. Plus you end up in the position of having similar validation code throughout your application, violating the DRY principle. In this video, I am going to introduce you to Fluent Validation, a free tool to help make your validation clean, easy to create, and easy to maintain. As a bonus, it even works on models that you don't own and cannot change.
    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

ความคิดเห็น • 282

  • @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!!

  • @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.

  • @DrWambua
    @DrWambua 2 ปีที่แล้ว +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!

  • @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 .

  • @96ziemniak96
    @96ziemniak96 5 ปีที่แล้ว

    Great job, first video and I'm in love with it! Keep going!

  • @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.

  • @sugamsingh5213
    @sugamsingh5213 5 หลายเดือนก่อน +1

    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 :)

    • @IAmTimCorey
      @IAmTimCorey  5 หลายเดือนก่อน +1

      You are welcome.

  • @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.

  • @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.

  • @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.

  • @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.

  • @LuigiZambetti
    @LuigiZambetti 5 ปีที่แล้ว +1

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

  • @pierreplourde
    @pierreplourde 2 ปีที่แล้ว +2

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

  • @scotolivera8207
    @scotolivera8207 3 ปีที่แล้ว +2

    Thank you, just what i was looking for

  • @ashishjain871
    @ashishjain871 4 ปีที่แล้ว

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

  • @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.

  • @jurgenbartalis1933
    @jurgenbartalis1933 3 ปีที่แล้ว

    What a brilliant and helpful video! I hope I get it adapted in WPF.

  • @webbi1540
    @webbi1540 4 ปีที่แล้ว

    Great video master Tim

  • @rennishj
    @rennishj 4 ปีที่แล้ว

    Thanks for this great video Tim.

  • @nhanth
    @nhanth 5 ปีที่แล้ว

    this video helps me a lot, Sir. Really love it.

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว

      I'm glad it was helpful.

  • @Dame4Lyf3
    @Dame4Lyf3 5 ปีที่แล้ว

    Great exercise on validation checks, and easily adaptable for my changes, this couldn't have come at a better time. Thanks for all your tutorials 👍🏽

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว

      You are most welcome. Thanks for watching.

    • @Dame4Lyf3
      @Dame4Lyf3 5 ปีที่แล้ว

      @@IAmTimCorey A follow up question, when you simulate an insert, would you add a check for user's with apostrophes in their name? i.e O'Hare etc, would creating a rule be a better approach or just stripping that value all together?

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว

      On the check side of things, I would need to update the letter check to handle the single quote/tick mark. On the inserting into SQL, I would allow it because that is a valid part of their name. If I use parameterized SQL (and I should), that won't be a problem.

  • @kojoig
    @kojoig 5 ปีที่แล้ว +1

    Thank you for this amazing video.

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว

      You are most welcome. Thanks for watching.

  • @Chivasque
    @Chivasque 3 ปีที่แล้ว +1

    Thanks Tim, you are amazing !

  • @RomuloMagalhaesAutoTOPO
    @RomuloMagalhaesAutoTOPO 2 ปีที่แล้ว

    Simply useful. Thank you very much Tim.

  • @n9434178
    @n9434178 5 ปีที่แล้ว

    Thanks Tim! Very useful.

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว

      You are welcome. I'm glad it was useful.

  • @bahrian4394
    @bahrian4394 ปีที่แล้ว +1

    This is a great video done sir

  • @lengsokpheakdey
    @lengsokpheakdey 5 ปีที่แล้ว

    Very great and useful tutorial Thanks Tim.

  • @gochadarjania170
    @gochadarjania170 2 ปีที่แล้ว +1

    Thanks for this video!

  • @daizwap9454
    @daizwap9454 3 ปีที่แล้ว

    amazing episode thank you Tim Corey

  • @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.

  • @movsar42
    @movsar42 3 ปีที่แล้ว

    This is so useful! Thank you!

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว

      Glad it was helpful!

  • @sweetsazd11
    @sweetsazd11 4 ปีที่แล้ว

    Great explanation! Thank you :)

  • @sagarharale
    @sagarharale 2 ปีที่แล้ว

    Really nice video, helps to reduce a lot of dirty code 👌

  • @milanmladenovic
    @milanmladenovic 5 ปีที่แล้ว

    Great video. Thanks a lot!

  • @guilhermegoncalves6529
    @guilhermegoncalves6529 4 ปีที่แล้ว

    Great! Thank you Tim :)

  • @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.

  • @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.

  • @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.

  • @MBlackAlpha
    @MBlackAlpha 5 ปีที่แล้ว

    Very helpful ! Hope they will be more tools like that, even if you don't like them too much.

    • @IAmTimCorey
      @IAmTimCorey  5 ปีที่แล้ว +1

      Thanks. I do like tools like this. I am just very careful which ones I invest time and energy into, since a tool can go away and then I can be worse off than if I didn't use the tool at all. Open source helps, since I can maintain the source on my own if I really needed to.

    • @MBlackAlpha
      @MBlackAlpha 5 ปีที่แล้ว

      ​@@IAmTimCorey Don't hesitate to show us more of them. I use Dapper a lot since I discover it with you and probably will add FluentValidation to my list of useful tool. Through your videos, I'm learning and discovering C# with a new (and better) eye and I'm very thankful to you for that.
      One suggestion of video is about managing huge amount of data : how to select them from database, display with pagination or in a datagridview, display a wait message with time remaining, manage mass update. For example I often have to treat sells from shops, I have to manage with a database containing every cash receipt and for example retrieve how much sells for one product in a given date period.

  • @Saleh-le2zf
    @Saleh-le2zf 3 ปีที่แล้ว +1

    THANK YOU!

  • @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.

  • @AshrafSada
    @AshrafSada 4 ปีที่แล้ว

    Thanks Tim

  • @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

  • @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.

  • @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.

  • @deeproy7292
    @deeproy7292 4 ปีที่แล้ว

    thank you

  • @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

  • @RalfsBalodis
    @RalfsBalodis 3 ปีที่แล้ว +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  3 ปีที่แล้ว +1

      Thanks! I added it to the description.

  • @wa1gon
    @wa1gon 2 ปีที่แล้ว +1

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

  • @khoadoo5505
    @khoadoo5505 3 ปีที่แล้ว

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

  • @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?

  • @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!!

  • @serhiihorun6298
    @serhiihorun6298 4 ปีที่แล้ว

    Thank you! Дякую!

  • @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.

  • @SadedeGel
    @SadedeGel 2 ปีที่แล้ว

    Great!

  • @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

  • @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

  • @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.

  • @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.

  • @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.

  • @DavidMartin-vs1dm
    @DavidMartin-vs1dm 2 ปีที่แล้ว

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

  • @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.

  • @santiagopiaggio2099
    @santiagopiaggio2099 4 ปีที่แล้ว

    Hey tim!
    Do you have any video regariding "JSONserializer" ?
    If not, do you have any to recommend?
    Thanks!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I use JSON serialization in the TimCo Retail Manager series (the WPF project gets all data from an API).

  • @phamthehung2
    @phamthehung2 2 ปีที่แล้ว

    Can fluent validation be used with WPF data binding?

  • @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.

  • @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.)

  • @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.

  • @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.

  • @MohammedIbrahim-hk2bp
    @MohammedIbrahim-hk2bp 3 ปีที่แล้ว

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

  • @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

  • @john_wick_v2gamer361
    @john_wick_v2gamer361 4 ปีที่แล้ว

    Hi, @IAmTimCorey do you advice against using error provider component?
    and thank you so much for your videos man...your a god sent. i am working on a complex software and i get a lot of valuable information from your videos.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Do you mean in WinForms? Yes, I do recommend you use it (or at least learn it). It isn't available in all UI projects, though, so we display errors in other ways.

    • @john_wick_v2gamer361
      @john_wick_v2gamer361 4 ปีที่แล้ว

      @@IAmTimCorey thanks, i will go and learn it...

  • @kunningdreamz
    @kunningdreamz 2 ปีที่แล้ว +1

    Can we pass a list of errors in the message?

  • @ilyubenok907650
    @ilyubenok907650 2 ปีที่แล้ว

    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

  • @techmarcs
    @techmarcs 4 ปีที่แล้ว

    Hey Tim, amazing video as always, thanks. I'm wondering how this will fit with the OCP design principle though should the constraints change in the future.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Good question and that's something you need to work through with your design. Since you can separate your validation from your model (into two files), you can keep your validation as having just one reason to change and keep it closed for modification.

    • @techmarcs
      @techmarcs 4 ปีที่แล้ว

      @@IAmTimCorey, sounds good. But just so its clear, you're saying its ok to "modify" the validation class if the validation rules change. Correct?
      PS: I understand OCP is a goal and not a rule but I'd like to see how to achieve it as much as possible because I've seen value in SOLID personally.
      PPS: Thanks for your response!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      This is where reality conflicts with ideal. In an ideal world, you would close the validation to change and just extend it (OCP). However, if the rules change, you need to change the class rather than just extending it. You would extend it if the rules were the same for some things but different for new cases. That is what OCP helps with. It doesn't help with foundational logic changing. If today 2+2 is 4 and you write a method that returns 4 and tomorrow I say that we made a mistake and 2+2 is 5, you would need to change the original method because it was a bug. Essentially that is what you are saying when you say the logic is different. The original logic was faulty. Now we are fixing that fault. Therefore, OCP doesn't really apply.

    • @techmarcs
      @techmarcs 4 ปีที่แล้ว

      @@IAmTimCorey, interesting thoughts. Thanks. Just to summarize. In this scenario, we have 3 unique cases;
      Case 1. Existing Rules change - Change the validation class.
      Case 2. Existing Rules are wrong - Change the validation class because its a bug.
      Case 3. New rules are added to existing rules - Extend the validation class. Do you mind expanding on how this will work practically? In this case, will you move out the rules from the constructor of the existing validation class or create a completely different class for these new rules? What will you do differently to make this validation class extensible? I'm worried that if we get into just extending the validation class through inheritance, we might get into an inheritance problem somewhere down the road.
      Again, thank you for sharing your thoughts through these videos and in the comments.

  • @javadjannesari9734
    @javadjannesari9734 2 ปีที่แล้ว +1

    gooood

  • @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.

  • @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.

  • @grantsamson2384
    @grantsamson2384 3 ปีที่แล้ว +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 3 ปีที่แล้ว +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  3 ปีที่แล้ว +1

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

  • @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.

  • @fj8551
    @fj8551 5 หลายเดือนก่อน

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

  • @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.

  • @ahmedmadhun2447
    @ahmedmadhun2447 4 ปีที่แล้ว

    Nice example, thank you.
    Is it possible to apply the validation only on a single property ?
    (There was not much useful examples on stackoverflow regarding this)

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Sure. You can leave the rest of the properties with no validation if you want.

    • @ahmedmadhun2447
      @ahmedmadhun2447 4 ปีที่แล้ว +1

      @@IAmTimCorey Yeah, but I am looking for a way to validate only a single property and avoid sending the whole object with empty values.
      I saw this at stackoverflow but didn't understood it:
      stackoverflow.com/questions/2850231/validate-a-single-property-with-the-fluent-validation-library-for-net#comment61658776_2850364

  • @MrBrouilles
    @MrBrouilles 2 ปีที่แล้ว

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

  • @OzgulEzgin
    @OzgulEzgin 4 ปีที่แล้ว

    Thank you very much for this video Tim. Great information. Now what if I want to bind the error messages to form controls like text boxes using errorprovider property of form ? Is it possible ??

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      That's a lot to cover in a post. Yes, you can bind the messages to error boxes on the page, though.

    • @OzgulEzgin
      @OzgulEzgin 4 ปีที่แล้ว

      @@IAmTimCorey thank you :) May be will be lucky enough to get another video on the subject then.. bests

  • @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.

  • @hom-sha-bom
    @hom-sha-bom 2 ปีที่แล้ว

    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

  • @erictenwestenend868
    @erictenwestenend868 ปีที่แล้ว

    How to set focus to the first invalid element?

  • @RalfsBalodis
    @RalfsBalodis 3 ปีที่แล้ว

    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  3 ปีที่แล้ว

      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).

  • @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.

  • @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 TH-cam 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.

  • @danielweaver6110
    @danielweaver6110 3 ปีที่แล้ว

    Do people use this kind of validation with backends using asp.net core and WPF using MVVM?

  • @mthraves
    @mthraves 4 ปีที่แล้ว

    Hi Tim. I would like the Admin User to be able to define what fields they would like to be mandatory. I'm looking to hold this info in a SQL DB. What tool/technique do you recommend to allow for this situation where the Validation can be user defined. I'm looking into FluentValidation to see if I can pass parameters to instruct it what rules to apply. Also, is this Validation only Server side or is there a way of getting it to work Client side too? Many thanks in advance.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Hmmm, I don't have an example of how to do this and I would probably need to try some things out to figure out the best way to do it. It would probably involve some custom validators and some custom JavaScript for client-side validation (or maybe some fun code for Blazor WebAssembly to run).

    • @mthraves
      @mthraves 4 ปีที่แล้ว

      @@IAmTimCorey Thanks for the quick reply Tim. I'll see how I get on with passing required field values to FluentValidation.

  • @Layarion
    @Layarion 4 ปีที่แล้ว

    bro what's a "BindingList" and "decorators"? I did a search for decorator on your channel and no video with a title using that word came up.
    anyway, so it actually is *okay* to do validation in the model layer? nice to know.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      A BindingList is a type of list that gives off a notification of property changed event when something is added or removed. A decorator is the items you put on top of your property ([Required] is a decorator). As for doing validation, couple things here. First, models are not a layer to themselves. In a MVC or MVVM framework, they are part of the UI layer (the whole pattern for each is the UI - they do not represent three layers). Second, you would only typically do validation in the UI layer on your UI models. So, if you got a model from your database, that model would not have validation on it. This is why you do a transform to a UI model if you need to add decorators (that's what we did in the TimCo Retail Manager series).

    • @CodySkidmorenh
      @CodySkidmorenh 4 ปีที่แล้ว

      docs.microsoft.com/en-us/dotnet/api/system.componentmodel.bindinglist-1?view=netframework-4.8
      code-maze.com/decorator-design-pattern/

  • @kitsurubami
    @kitsurubami 4 ปีที่แล้ว

    if you have no control over the library, would it be bad to create a brownfield library and store validation there?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Not sure what you mean by brownfield (typically it refers to existing application code). Can you clarify?

    • @kitsurubami
      @kitsurubami 4 ปีที่แล้ว

      @@IAmTimCorey I'm sorry, my initial question was a bad question. At 28:36 of your refactoring in C# video you created a new library to an existing application and named it BrownFieldLibrary. At 6:33 of this video you were discussing how you may not have control of the class library, and at 7:14 you said you were going to put it in the front end, because you were simulating having no control over the library. With all that in mind, my question is "couldn't you have added a new library next to the library you have no access to?" At least for the simulation, you are adding validation to an existing application code, that's why I was saying a brownfield library. Thank you for your videos and your replies. I'm learning a ton. I'm particularly interested in best practice for where to put code.

  • @dookie8414
    @dookie8414 4 ปีที่แล้ว

    for MVC application is it a best practice to use Fluent Validation?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      Best practice? No, but it is a valid choice.

  • @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!

  • @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 2 ปีที่แล้ว

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