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!
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!
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.
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.
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.
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.
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.
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.
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?
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.
@@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!
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
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.
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.
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.
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" :)
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.
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.
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.
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 😁
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.
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.
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.
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?
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?
"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
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).
@@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!
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...
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?
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
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.
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.
@@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.
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
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!
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!!
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.
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
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).
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
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.
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.
@@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
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?
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.
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.
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.
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.
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.)
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!
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!
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.
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; } }
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.
My favorite youtube programming channel.
Awesome!
Same!
Guys, I think Tim deserves so much support on patreon, he is an amazing teacher. Thanks Tim!!
Thank you!
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 :)
You are welcome.
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!
I'm glad you enjoyed the video.
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!
You are welcome.
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!
You are welcome.
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.
Thanks for the recommendation! I'm glad you are enjoying it.
Upwoting this video before I see it since I know it will be good.
:-) I'm glad you have confidence in me. I hope I never disappoint.
Also in this week I've learned something new. Thank you Tim.
Great!
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.
It is on the list. Thanks for the suggestion.
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.
You are most welcome. Thanks for watching.
Thank you, just what i was looking for
Excellent, glad it was helpful!
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.
Thank you.
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.
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.
Thanks Tim, you are really talented, not only in programming but also in explaining it.
I appreciate the kind words.
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?
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.
@@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!
Thanks for the video. Clear, easy to follow and helpful :).
You are welcome.
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
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.
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.
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.
I'm not really following but I'm glad you figured out how to get it to work.
Very great and useful tutorial Thanks Tim.
You are welcome.
Thanks for this great video Tim.
You are welcome.
amazing episode thank you Tim Corey
You are welcome
Thanks for this video!
You are welcome.
Great video master Tim
Thank you!
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" :)
That is pretty cool. They baked some nice features into the product.
Great explanation! Thank you :)
You are welcome.
This is so useful! Thank you!
Glad it was helpful!
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.
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.
Sorry but I think you missed my point. Nothing to do with the length of a line of code.
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.
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 😁
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.
Is there a way to define the alignment of the data validation memo...the leftmost column ends up cutting off half the memo box
Hi Tim, have you in plan to make a future video about WCF? (that is still used in enterprise applications).
It is on the list but it keeps getting pushed down by higher priorities.
Great video. Thanks a lot!
You are welcome.
THANK YOU!
You are welcome.
Great! Thank you Tim :)
You are welcome.
Why I have to instance model if the flunt library extends it
Hi Tim,
Is there a way that I can reuse validation from PersonModel to CreatePersonModel without checking field ID?
Great Course thanks! Do you do personal trainings as well?
Thanks and no, I do not. I don’t have time to do personal training anymore.
@@IAmTimCorey Bummer, appreciate the reply. Good Luck.
Thanks, useful! Not possible to show the error in real-time under the associated TextBox? More user-friendly.
Thanks for watching and sharing you thoughts. I'm all in for more user friendly!
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
Yep.
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
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.
Could you please make a video about application localization?
That is on the list. Thanks for the suggestion.
Thanks Tim
You are welcome.
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.
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?
You can do something like this: stackoverflow.com/questions/21115179/fluentvalidation-check-if-one-of-two-fields-are-empty
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?
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
I want to get the response of validations in xml format, can someone help me please?
"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
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).
@@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!
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...
The output of one method is used as the input of the next method. That is how it knows the order.
Is this related to Blazored.FluentValidation (from Chris Sainty)?
Can fluent validation be used with WPF data binding?
How to set focus to the first invalid element?
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?
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.
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
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.
oh , which one do you think is better to implement?
@@IAmTimCorey
Thank you! Дякую!
You are welcome.
What about Data Annotations, do you prefer one over the other? Thanks
These are more powerful but they take more setup work. I typically stick with data annotations until I need more power.
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.
Why and how {PropertyName} display "First Name" instead of "FirstName"?
Because one of the attributes we applied was to rename the property for display purposes.
I downloaded the startcode, but it has no dependencies so I can't add reference and download the fluent. Anybody have experienced the same?
Not sure what the issue is. Is the project still a .NET Framework project or did it somehow get converted to .NET Core?
@@IAmTimCorey Thanks for your answer, I´m not sure how to tell but looking in the dashboardUI.csproj, v4.7.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.
Yes, you can do that. Just be careful not to make a really messy validator.
gooood
Thanks!
Just a little off-topic hint: When you do: "if (condition) return true; else return false;"
You can simply do instead: "return condition;"
Yep. I usually point that out. The if statement is just a bit more readable for new developers, though.
Please don't use a demo project. How can we learn how real-world project looks like and how they are organized?
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.
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.
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.
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??
Correct. I am very exclusive with who can use my applications.
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
Thanks! I added it to the description.
I think it would be better to have the error message popping up as a tooltip inside the field.
Go for it. Try it and ask folks for feedback. Its the real world way to build skills.
easy, use errorprovider with it.
I don’t have comments, I’m speechless Sir!!!
I'm glad it was valuable to you.
This one is worth the price of admission!! Great video and good information.
Thanks!
I like it too. Thanks Tim.
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.
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.
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!
You are most welcome. Thanks for watching.
Can we pass a list of errors in the message?
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 .
You are welcome.
Thanks for this great video! But the link for source code on one drive is not valid anymore. Can you share it again? Thanks.
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.
@@tomthelestaff-iamtimcorey7597 Too bad :/ Anyways, thanks for letting us know
Thank you for this amazing video.
You are most welcome. Thanks for watching.
Hi Tim, I love your videos, but it would be lovely to have Advance Fastrack version of these videos for reference.
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.
@@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.
Great video. It would be nice to have one using Blazor.
Thanks!
Thanks Tim, you are amazing !
You are welcome.
Sir, could you please show how to use fluent api in an MVC form?
Topic suggestion noted and added to my list, thanks.
@@IAmTimCorey thank you so much sir!
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
I thought you are Mosh :(
Nope, sorry.
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!
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!!
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.
Cool!
Will this work for WPF?
Yes it will.
"Never trust the user!" Made my day :D
ruclips.net/video/Zh1ccvTFzs8/видео.html
Btw thanks, great video!
This is a great video done sir
Thank you!
Little Bobby Tables.
XKCD FTW
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
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).
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
It is possible. However, you need to be careful since you might want to validate just a bit differently down the road.
TotalLength doesn't work and I don't know why there is no solution
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.
Thanks! We really appreciate your contributing by sharing your thoughts.
Cool.
So if you have a winforms with say 30 text boxes, do you use this "Fluent Validation" for ALL of them?
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.
Best teacher....
Thanks!
@@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
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?
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.
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.
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.
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.
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.)
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!
You would probably break the model up into models per form.
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!
I think you are on the right track. A custom validator is probably your best option.
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.
That would be some extra work but I think it could be done.
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;
}
}
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.
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
This video on Combobox from Tim may help - ruclips.net/video/nKJ_XDoAdtY/видео.html