Hey guys,
How are you?
Form validation, if the e-mail is filled, if the field is correct… These are parts used in registration or “Input” screens in applications.
Several validations can be done for this field type, including one using masks, as demonstrated in this article.
There is another excellent way for those who are used to working with C# and want to carry out validations: It is possible to use the Famous Fluent Validation! Yes, the same one you use in your Web applications, APIs, etc.
Let’s see how?
Setting up Fluent Validation and our example
First of all, let’s go to our dear Nuget to install the FluentValidation Package in our shared project:
To make our life easier, we will add MVVM Helpers, which you can see how to do in this article by clicking here.
Easy! Now let’s prepare our project by creating a simple Model:
And our screen:
Okay, with that we can play with Fluent.
Using Fluent Validation
Let’s create a Validator for our Person model by implementing an AbstractValidator, thanks to which we can define Roles for our properties:
The idea is simple: use RuleFor for which field you want to validate, then the rules you want to use. Note that in all of them, I put that it must not be null or empty followed by a WithMessage.
Note that in all of them, I put that it must not be null or empty, followed by a WithMessage. It is possible to use a specific WithMessage for each type of Validator, as I did in the E-mail using an EmailAdress role.
Several Validators can be used, and you can check the complete list here. It is possible to create your own rules, which build an incredible range of possibilities.
Alright, now let’s implement validation by pressing the validate button:
We must declare our validator and call the Validate method passing our Object. Done! Fluent does everything for us, including sending us an error list with all the incorrect validations:
Very cool isn’t it?
There are other really cool features in Fluent, and if you want, I’ll do a part 2 showing more things :).
If you want to see an example cited in the article: Click here.
Want to see other articles about Xamarin? Click here.
I hope this helps!
All the best!
*The content of this article is the author’s responsibility and does not necessarily reflect the opinion of iMasters.
Leave a comment