WPF Data Validation - Exception, IDataErrorInfo, ValidationRule, & Annotations

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys toss car here and in this video we're going to cover multiple ways that we can do validation in WPF now unlike my other videos because we're covering multiple ways over here I've already created some projects and we're gonna go through them together now for our first part you'll notice that I already have an observable object and a view model and a basic layout if you'd like to follow along there's actually a project on my github you want to follow along just go to this link you can clone or download I recommend downloading this zip and then you can unzip it and then open it in Visual Studio and in here you're gonna see all the projects that we're gonna cover in the video but then I also have a fourth project here which has the basic template of what we're going to be working with and then you can use this project to follow along so what I mean by data validation is for example we have our text box here and when we enter in let's say we want to do a registration form and we're entering in a user name now this user name may have a requirement of let's say at least 5 characters and we want the textbox to perhaps highlight and read or show an error message if the current user name that is inputted is not valid now over here on our project for our first one we're actually going to do this by throwing an exception so we're gonna go to our registration view model and the only thing we're really gonna do here is over in our setter for our property we're going to create an if statement so if string is null or whitespace we're gonna give it the value and if this is true then we're just going to throw a new argument exception and we're going to say the user name cannot be empty so to begin all we're going to do is we just can't have an empty username now using exceptions for validation is very convenient but it's not always an appropriate way to do it an example of when we would maybe not want to use this is if a common invalid state can be abstracted so if we're having minimum characters and we're also going to have other fields with minimum characters we may not want to do this to each and every property it may also require a combination of values not just this one property but moving on over here we're going to go back to our main window and we're gonna go down to our zamel and then the first thing we want to do of course is go to our text box and we want to bind to the text property here binding and we're going to bind of course to the username that we created and before we do anything else I just want to run the application it's now our application running we can see as we type nothing really happens and then when we read when we erase nothing really happens but then of course to update the property we want to change control so I'll click the button now the button doesn't really do anything this is just updating because now I've switched the focus but we see here it's gonna throw an exception now the throws an exception for you you want to go down here to exception settings and then untick break when this exception type is user unhandled and then click continue now we have our user name again and then as we erase and change focus nothing really happens and then we'll see even down here it's going to throw some exceptions in our console now back here to our zamel what we want to do is within the binding we want to get the validates on exceptions and we want to set this to true and then we also want to update the source trigger to property changed so we don't have to click the button to update it and then now when we run the application as we type and then as we erase we see that it's going to highlight our text box here with a red border and then as we enter a character it'll go away and then as we remove it it'll be there as well so that's one way we can go about it we can also go next over here to our validation by the data error info interface now over here in our data error info we have pretty much the same setup here just to username and a button and then we're gonna go to our registration view model real quick and then in this view model what we want to do is we want to get the eye data error info interface here control period and enter in the using statement for component model and then we can hit control period again to implement the interface now the first thing we'll notice here is we have a little public string here error this we're actually not really going to use in WPF won't call this so we're just going to get and return null and then push this up here next we're going to have this index or here and this we're just going to erase the implemented not a not implemented exception and we're going to rename this here to just name now what this does is provides a property to evaluate so if we have an error we want to provide an error message or return one and if no error occurs then we just want to return null so we're going to setup a get accessor here I'm just going to create a string here called result and initially set it to null next we're going to do a switch and we're going to pass it the name that we're given and in this case if the case is username so that's the name of the property that we're going to evaluate then we're going to call an if statement here like we did before we're going to do a string is null or whitespace a name a rather not name the actual property we want to check user name and we want the result to equal user name cannot be empty and we want to do else if user name length less than 5 so if our user name is less than 5 characters and we want the result to equal whoops user name must be a minimum of 5 characters and then we just want to call a break now of course we're still gonna have an error because if none of these cases exist and we still need to return something and we'll just return their results because if it doesn't hit anything it'll then return null indicating no error so next we're going to go over here to our solution Explorer go to our main window down to our zamel and we're gonna do something similar we're gonna get the text prop the text property of course we're going to do binding to the user name but now when we do not the update yet and do validates instead of validates on exceptions we're going to do validates on data errors and we're going to set this to true and then of course now do our update source trigger to property changed it's now when we run our application we see by default here it is red and then even as we type a character it's still red this is going to happen until we get to one two three four and then five characters here now it'll go away now basically what you may be thinking is it feels like we did a little more work here than the other one and they both do the same thing well now we're gonna do something a little extra to the view model we created so now here on our view model we are returning multiple results but this really doesn't do any help because all we really have is a red box so there's really no point in even returning any kind of error message so what we're gonna do next is up above here we're going to create a public dictionary composed of a string key and a string value and we're going to call this error collection and we're going to do a get private set and just for now we're just gonna by default instantiate it so it's not null now next down here after our switch we scroll down a little more after our switch we want to do if we want to get our error collection here if it contains a key for the property that we're checking and we want to go to the air collection name and we want to set this to the new result that we have and we want to do an else--if because remember we may not always be throwing an error so we can do results equals null or rather does not equal null which means we do not have the key but we do have a error then we're going to add to our error collection here a name and the results and now because our error collection has been updated we want to do an on property changed error collection so now what we're doing is creating a dictionary for certain errors that we're going to have and the reason we're gonna do this it's because it's now over here in our main window I'm gonna go down here to our zamel and next what we're going to do is we're going to go to the tooltip property going to be binding error collection which may not show up in intellisense just yet and we want to get the key user name so now here when we hover over our textbox we see we get a tooltip saying the user name cannot be empty then as we add in a character here and we go over it the tooltip will change to the user name must be a minimum of 5 characters [Music] [Applause] now the next project we want to work on here is go over to our validation by custom and again we have the same layout as before and now in this case we're actually not going to really need to touch our view model at all I'm gonna go over here to our project and we're going to add a new class and we're going to name this new class here minimum character rule and add and then though here in our class we're gonna make this of course public you then want to derive from validation rule add in the name space of window system that windows controls and then in here we're gonna have a public integer this will be called minimum characters so we can set how many characters are limited and we're just gonna do a get set because we will be binding to this a rather setting this in our zamel and then we want to go to override and we want to find the override for validate in this case we'll just do the parameters with object and culture info and then here I'm just going to create a string we're just going to call it char string you can give it a better name if you'd like we're going to get the value as a string and then we're gonna do we're going to check the star string here or a length and see if this length is less than the minimum characters and then if it is we're going to return a validation result but actually here we're forgetting our new keyword so a new validation result can I do all because it is not valid and then we're just going to do a string here and use at least we're going to put in our minimum characters here and say characters then if it doesn't hit this then we're going to return a new validation result in this case it'll be true so it is valid and then we need to know we'll just use null for the error content so now if we go over here to our main window and we go down to our zamel and we go down here to our text box we're going to do something a little different here just gonna have opening and closing tags for our text box we're going to access the text box dot text and then in here we're going to set up a binding the path will be to our data context which is the view model so the path will be to the username property we want to set the validates on errors and data errors to true and then update the source trigger to property change and we'll close that off and now what we're going to do is when access binding validation rules and then we're just going to go to our local XML namespace here and we're gonna find our minimum character rule now if you remember we made a property in here as well so we'll go to minimum characters and we'll set this to 5 now when we run our application we won't have an error because we didn't set up a rule for the username not being allowed to be empty but then as we type here we see that we're still gonna have an error now we didn't set up an error message in here but we could and now if we just do one two three four and then we get to our fifth character here we no longer have an error now I bet by now you're wondering well I actually want to display a message I don't want to use a tooltip I don't just want a red box I actually want to display some kind of red error message to the user on the control well luckily we can actually set up an error template here so we're gonna go over here to our app dot zamel and in here we're gonna set up a control template and we're gonna give it a key and we'll just call it error template you want to of course give it a border because we're going to override the error template so by default it'll give a red border but now since we're gonna override it we need to set a new one and we'll give it a border brush I'll say orange red and I'll give it a border thickness of two and we'll open that up and then we'll just do a simple grid here no special properties to it now what we do need is an adorned element placeholder this indicates where the original content will be placed so we're just going to keep that there but then next what we want to do is a text block you want to do text and this text block is going to be our error message we want to do binding and we're gonna do in a rate indexer of zero and dot error content now when we override the error template it's naturally going to have an error content it's also going to have a collection now what this zero here indicates is that we just want to return the message of the first error that we have we don't want to display all of them we just want to let them know what the first error is we then want the foreground here to be like the border orange red you don't want to do let's say a vertical alignment in the center and then a horizontal alignment to the right so the error message will be in the center right of the text box and then we want to push it away a little bit so we're gonna give it a little margin from the right here of four and then close off and now when we go over here to our main window go down to our zamel go up here to our text box and we want to get the validation dot error template and we're going to give it the static resource here of the error template we created now when we run our application as we type here we'll see that we'll actually here get an error template and we set it so the user whoops must have missed felt that but you get the point the user must have at least five characters then as we type we're still gonna get that error and then of course when we meet the validation it'll go away and then come back and you can also use this for all the other validation methods that we used as well now because I want to reuse this and we're gonna move on I'm gonna copy and paste this control template here I'm going to go over to our validation by annotations we'll open up that app that sam'l real quick and we'll put in our control template again just so we can reuse it and now we want to open up our main window and our registration view model and now in this case we're just gonna jump right to our registration view model but actually there's one thing we got to do to use the data annotations we actually have to add in a reference here so we'll add references then here in our assemblies as we have a whole list we're just going to type in annotations and then we'll find here the reference for the system dot component model data annotations we want to tick that and then click OK close our references now and go back over here to our registration view model and now the first thing we're going to do is over our property here we're going to get a required attribute here we're gonna have to add in of course the reference that we just created and what the required attribute indicates is that the property's value cannot be null or empty if you guys are familiar with asp.net you've probably used these and then in here we're going to set the error message here and we're just gonna say must not be empty and now we also want to limit the character rule and we can get another data annotation that we have called string length but it limits the maximum and minimum characters here I'll do 50 and we'll set the minimum length here to 5 and then we'll get the error message here must be at least 5 characters now by default this isn't just going to work we actually have to use the component model down annotations validate property so scrolling down here we want to do a say public or private boy call it validate property we'll take a type of T then T of course will be devalue and string name then here we're going to call the validator validate property and we're going to pass it of course the value here so this is what we're going to be validating and then we'll create a new validation context this is the object instance in which the object exists the rest we can just do null and then within the validation context we want to set the member name property here to the name and of course at a semicolon at the end and actually these always screw me up don't need one there so now if we go over here we're going to go over to our main window go down to our sam'l and then here in our text box I'm going to get the text property plus going to bind to the username in this case we're going to do a validates on exceptions to true then going to update the source trigger here's a property change like we always have and then of course we want to access the validation error template and give it the error template we created for the last project and now when we run the application we see as we enter in characters here we're not really getting anything and as to remove it we're still not now the reason we're of course not getting an error is we actually never called the validate property that we just created so sorry to you guys who are probably yelling at me while you're watching the video and saw me skip over it so then here we're just going to pass a force the value and then the user name that's the name of the property we see that as we answer character we are going to get an error real quick go to our exception settings will break when this exception type is user unhandled we'll hit continue so we won't get that anymore and then now as we enter we'll see it'll go away and come back so guys that's really it for the data validation in WPF I hope you enjoyed like subscribe if you have any questions leave them in the comments and tell me which method you think you would prefer I personally think I like the annotations but anyways guys thanks for watching
Info
Channel: ToskersCorner
Views: 23,629
Rating: 4.9726028 out of 5
Keywords: Programming, tutorials, C#, .Net, learn C#, C# tutorials, WPF tutorials, programming for beginners, visual studio, microsoft, code, coding, wpf, validation, data validation, exception, IDataErrorInfo, ValidationRule, Annotations, Error Template, ValidatesOnException, ValidatesOnDataError, textbox, text box, validation tutorial, how to
Id: 5KF0GGObuAQ
Channel Id: undefined
Length: 21min 57sec (1317 seconds)
Published: Tue Jul 24 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.