Using FluentValidation in ASP.NET Web API for Model Validation (Implemented in .NET 6 and C# 10)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dotnet course central in today's video i am going to talk about fluent validation in asp.net core and this is the nuget package that i'm going to walk through which is fluentvalidation.asp.net core in my previous video i discussed about how to use the out-of-box validation framework to validate model in asp.net core web api in today's video i'll show the same thing but using fluent validation now the question is why would i use fluent validation the reason for using fluent validation is it is much more powerful than the out-of-box validation framework to do that let's first start with deleting this interface we would not need this for this example so i'm going to get rid of that and i'm going to get rid of these few of these as well because we are going to use fluent validator to do all this so now as you can see the model is pretty straightforward there is no separate attribution that we need in the data model and the entire validation can be provided in a complete different class and that is what we are going to do so what we will do is we are going to create a new class and i am going to name it as user validator and inside user validator is where we are going to write all the validation so for that purpose the user validator is going to derive from abstract validator which is provided by the fluent validation framework and it's a generic class which we are going to provide user as the type and then the entire validation setup happens at the constructor so we're going to create a constructor and here we are going to write all the validations and validation method usually starts with rule and as you can see you can use rule for rule forage or rule set ruleset is something we are not going to discuss in this video we are going to focus mainly on rule 4 and rule for each these two will probably be used mostly in asp.net framework so first let's start with rule 4 so if we want to set up a rule then we can start here so we can say user and let's say we want to validate the user name so we can say user.name and then here we get a lot of option so the options we can get is email address which we can use for email property empty for validating mt and then you can see greater than inclusive between there's a lot of options so let's start with one by one so for the name we are going to check if it is not null and then it is not empty so these are the two options we are going to check for name and for address and let's do the email for email we are going to say it's an email address so it'll validate that it is an email address and then let's do the address now and for address we can say that the address is not null and then we can say okay address is not null and the maximum length of address is 10. see so that's one option the other thing let's say we want to do is we want to make sure that the address contains a text street so we can say rule for dot address and we can say dot and for figuring out that specific logic what we can do is we can use a predicate and for that we will use this particular method which is must and here we can say address address dot contains and we can say here we can say straight and for this one we can say address question mark dot to lower dot contains equal to street true because we are using a question mark symbol we have to specifically say what the value is whether it's a true or false so that's about it so we can do that so if the address contains the value street then this is a valid rule so we can finish it here let me get the mast into the next line for better visibility and now let's just finish here let's start and then we are going to do a couple more modification into these and then we'll go to the next set of validations so let's run this application now so now here we can go to this post try it out and for if you just try it out as is nothing is working is because we have not set anything up yet so what we have to do is first we have to go into program and we want to make sure that we set up the fluent validator and for that what we can do is we can come here and we can do dot add fluent when validation and let me add this namespace for invalidation.sp.net core and then here we can provide the configuration and for that what we can do is we can say let's do dot we want to register the assembly so we can say register validators for this assembly and here we can say assembly dot and we have to add the namespace system.reflection so we can say assembly.get executing assembly so all we need to do so now the fluent validator is configured for all the controller so i'm going to restart the application and once the application is restarted and swagger is loaded we can go and verify the same thing again so we are going to go here try it out and let's just run this and now we can see the error email is not a valid email address and address does not meet the condition for address so for email it's a pretty straightforward message let's try it out but address error is still coming but as you can see the address error message is not very specific it's very hard to say what condition it is not meeting but we know the code so we know we have to provide street here so if we execute now we should get 200 success back now to fix the error message what we can do is we can go back here and here we can say dot with message and for the message we can say address must contain straight as simple as that let's try to hot reload but let's try it out now give at the rate email.com and execute and this time we can see appropriate error message address must contain street so this is as you can see the first advantage of using fluid validation is you don't have to do anything with the model itself everything can be handled outside of the model plus you get a lot of feature and options out of box and then this must with the predicate gives you the power of doing anything that you want to it but it is still not that convincing so let me put some more features into the application and see few more powerful reasons to use fluent validator so now what we are going to do is for the user object for the membership let's make it membership as an object so we can create a public record membership stream let's say that's the membership and here we can make it as membership array and let's rename it to memberships and now what we want to do is we want to validate the item inside of membership so for doing that what we can do is we can do rule for each this time and here we can say user dot membership and then for the memberships now we can go and do some validation so first we can do is membership dot child rules and here we can say membership say membership dot rule for and we can say user x goes to start name this is the name and we can say the name cannot be empty it cannot be no so that's the check we are going to do and this what it is going to do is it is going to do through every item and verify that it met the criteria so now let's rerun and test it out this is the existing validation from the previous code i'm just going to comment it out because we are not using this is from the previous video that i did so i'm just going to comment it out and run and now i'm going to go and try it out and let's make this as well.com and here if i said the membership is empty let me fix the address also let's make it as straight and if i said the membership is empty and now try to execute we can see here name must not be empty the error that we were expecting the other thing what we can do is now you can see the code is making becoming complex here and there's a lot of stuff going on here so what we can do is instead of doing all this thing we can create another class say public class and we can say membership validator is going to be driving from the extract validator and here similarly we can have a constructor and here we can have the same rule for what get it here so we can say rule for name not not and not empty and then instead of doing the child rule set what we can do is we can do here set validator and we can just say new of membership validator that's all we need to do and now instead of doing all the logic here we just move the logic of membership out into its own class and that will make this part of the code very clean so now if we run this we should see the exact same behavior as before so go here try it out let's make it s and the address straight and let's make it as empty execute and we can see the same error name must not be empty now as you can see this code is becoming big and for a big model it will be a lot of code and we might want to break things out into separate classes so do that what we can do is we can create two different classes so let's say we want to keep simple validation in one class and complex validation in another class so we can create public class user simple validator and it will be abstract validator of user and here we'll have the constructor and in the constructor we can get all the simple rules out and move them here and similarly we can create another class user complex validator which again is from abstract validator user and then we can move the complex validation into its constructor and now we have two classes but we still want to use user validator as the main one so what we can do is we can now combine these two and the way to do it is pretty straightforward what we can do is here we can use include new user simple validator include new user complex validator and now if we run this application we'll see the exact same behavior as before so as you can see there are a lot of way we can do the validation and we get to do a lot of complex stuff very easy way and with an extremely fluent api as you can see the api is very fluent and now we can move this class into all these classes into their own file and write very clean code and it will be extremely easy to implement that and now the other thing we can do of course is as i mentioned that if we want to use the validation outside of the controller so we do not want to [Music] not necessarily we do not want to we want to do this kind of validation but we might want to do the validation of a model at a lower level and let's say in the get here this get method takes name and address and we want to validate i have to get rid of this name and address and we want to validate the name and address somewhere down the line and we will create a user object from this name and address and pass it to let's say uh user manager so let's create a user manager class so we're going to go create a new class and i'm going to name it as user manager and let's fix the namespace and user manager class will have public sync tasks manage user and here what we can do is we want to do the validation so for validation we want to validate user so we will be injecting something called as i validator which is an interface and it is also a generic interface so we'll use i validator of user and the validation framework will automatically inject the appropriate validator so i'll create a constructor for that and here we'll say i validator user and we will add the namespace fluent validation for that let's declare this field and here what we can do is we can just do evade validation dot validate is sync we are not going to use validate testing because validate async returns a validation result which we'll have to use to figure out whether it's valid or not instead we can just use validate and throw which is going to just throw an error if validation is failed now this will give a lot of text trace and if we want to control that of course we can just use validate and then use the validation result to throw appropriate error message but for the time being i'm just going to use validate and throw and then what i'm going to do is i'm going to extract an interface and then the next thing i'm going to do is i'm going to go here i'm going to add a controller i'm going to add a constructor and in the constructor i'm going to inject i user manager edit field and here what i can do is i'm going to change this to async task action result and then here i can do evade user manager dot manage and here we're going to send the new user and for the user going to pass the name is equal to name and address is equal to address that's about it but we need to register the user manager into the dependency injection so we're going to go here and we can say builder dot services dot and for the lifetime we are going to use add scoped the reason for that is that i validator is a scoped lifetime object so here we have to use code for i user manager as well and then here we just added fluent validation to controllers but we have not done anything for rest of the service so for that what we'll do is we'll use builder dot services dot add add validators from assembly containing user validator and i'm going to add this namespace which is just the fluent validation what this method is going to do is it is going to now inject the eye validator of user into the dependency injection container which can be accessed by the controller so now let's run this application again and this time we are going to test the get method so one huge difference that you can see between the fluent validation versus out-of-box validation is that fluent validation can be used down the line in the api not just part of the api and which also means that fluent validation can technically be used inside of console application or long-running jobs so i'm going to try our test test and let's run and if we run we get an error here address mask contains street as expected and as i mentioned earlier it will have all the stick trace and we can get rid of that if we manage the error appropriately so as you can see the fluent validation can be used out of box with the api as well as internally in other classes or even console application so if we are using console application though then we are not going to add the fluent validation.asp.net core nuget package we're going to just use the fluent validation you get package as the asp.net core part is not needed but for our purpose we added the fluentvalidation.sp.core which internally have a dependency on fluid validation which also is added as a part of this nuget package so if we go to dependency if we exp expand the package and expand the fluentvalidation.asp.net core we can see fluent validation is also added as a part of this package and as you can see fluent validation makes validation code extremely powerful plus it makes it very clean because now you can add a complete new folder and you can have multiple class for validating all your model in one place and then it can be used not only in asp.net core application but in a console application for example if you are building an asynchronous microservice and you want to validate the method both in your api as well as your asynchronous microservice you can do that by moving your model and their validation into a common nuget package and using that across different services so that is all i wanted to cover for today's video if you like this video please give me a thumbs up if you are new to my channel and if you think you are getting value out of my channel please subscribe to my channel and thanks so much for watching this video
Info
Channel: DotNet Core Central
Views: 17,589
Rating: undefined out of 5
Keywords: fluentvalidation, fluentvalidation .net, fluentvalidation .net core, fluentvalidation c#, fluentvalidation dotnet, fluentvalidation dotnet core, fluentvalidation model validation .net, fluentvalidation model validation .net core
Id: sjhffFTV79Y
Channel Id: undefined
Length: 26min 6sec (1566 seconds)
Published: Sun Mar 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.