Introduction
Fluent Validation is used to create the validation logic separate from business logic for any type of object you want to validate. It's a kind of cross-cutting concern in application development and providing validation in the Aspect Oriented Programming structure.
Let us see how we can achieve the fluent validation in our Xamarin forms applications.
Implementation
Open Visual Studio and select New Project.
Select project type and give this project a name.
Select the template as Blank App and code sharing as PCL.
Set the target and minimum platform versions that your application will support.
Set the below configuration.
Open "Manage NuGet packages for Solutions" and install the following components.
The ViewModel directory will be added. This contains two files - MainViewModel.cs and ViewModelLocator.cs.
Create the Models folder and add the following files.
- Create file cs.
- namespace FluentValidationDemo1.Models
- {
- public class User
- {
- public string UserName { get; set; }
- public string Password { get; set; }
- public string ConfirmPassword { get; set; }
- public string Email { get; set; }
- }
- }
- Create file cs.
- using FluentValidation;
-
- namespace FluentValidationDemo1.Models
- {
- [FluentValidation.Attributes.Validator(typeof(UserValidator))]
- public class UserValidator : AbstractValidator<User>
- {
- public UserValidator()
- {
- RuleFor(x => x.UserName).NotNull().Length(10, 20);
- RuleFor(x => x.Password).NotNull();
- RuleFor(x => x.ConfirmPassword).NotNull().Equal(x => x.Password);
- RuleFor(x => x.Email).NotNull().EmailAddress();
- }
- }
- }
We have to define the validation attributes for the class you want to validate.
Inside ViewModel folder, create a file named SignUpPageViewModel.cs.
- using FluentValidation;
- using Xamarin.Forms;
- using FluentValidationDemo1.Models;
- using GalaSoft.MvvmLight;
-
- namespace FluentValidationDemo1.ViewModel
- {
- public class SignUpPageViewModel : ViewModelBase
- {
- public User UserObj { get; set; }
-
- private string _username;
- public string UserName
- {
- get
- {
- return _username;
- }
- set
- {
- this.Set(ref this._username, value, "UserName");
- }
- }
-
- private string _password;
- public string Password
- {
- get
- {
- return _password;
- }
- set
- {
- this.Set(ref this._password, value, "Password");
- }
- }
- private string _confirmPassword;
- public string ConfirmPassword
- {
- get
- {
- return _confirmPassword;
- }
- set
- {
- this.Set(ref this._confirmPassword, value, "ConfirmPassword");
- }
- }
- private string _email;
- public string Email
- {
- get
- {
- return _email;
- }
- set
- {
- this.Set(ref this._email, value, "Email");
- }
- }
-
- private readonly IValidator _validator;
- public SignUpPageViewModel()
- {
- _validator = new UserValidator();
- }
- private Command signUpCommand;
- public Command SignUpCommand
- {
- get
- {
- return signUpCommand ?? (signUpCommand = new Command(ExecuteSignUpCommand));
- }
- }
- private string _validateMessage;
- public string ValidateMessage
- {
- get
- {
- return _validateMessage;
- }
- set
- {
- this.Set(ref this._validateMessage, value, "ValidateMessage");
- }
- }
- protected void ExecuteSignUpCommand()
- {
- UserObj = new User
- {
- UserName = _username,
- Password = _password,
- ConfirmPassword = _confirmPassword,
- Email = _email
- };
- var validationResult = _validator.Validate(UserObj);
- if (validationResult.IsValid)
- {
- ValidateMessage = "Validation Success..!!";
- }
- else
- {
- ValidateMessage = "Validation Failes..!!";
- }
- }
- }
- }
Rename the file MainPage.xaml.cs to SignUpPage.xaml.cs. Open App.xaml.cs and change the below constructor code.
The directory structure will be as follow.
Open SignUpPage.xaml from Portable project and modify the content as below.
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- xmlns:local="clr-namespace:FluentValidationDemo1"
- xmlns:val="clr-namespace:FluentValidationDemo1;assembly=FluentValidationDemo1"
- xmlns:vm="clr-namespace:FluentValidationDemo1.ViewModel; assembly=FluentValidationDemo1"
- x:Class="FluentValidationDemo1.SignUpPage" BackgroundColor="Cyan">
- <ContentPage.Content>
- <StackLayout>
- <StackLayout.BindingContext>
- <vm:SignUpPageViewModel />
- </StackLayout.BindingContext>
- <Label Text="UserName" />
- <Entry Text="{Binding UserName}"></Entry>
- <Label Text="Password" />
- <Entry IsPassword="True" Text="{Binding Password}"></Entry>
- <Label Text="Confirm Password"></Label>
- <Entry IsPassword="True" Text="{Binding ConfirmPassword}"></Entry>
- <Label Text="Email"></Label>
- <Entry Text="{Binding Email}"></Entry>
- <Button Text="Submit" Command="{Binding SignUpCommand}"></Button>
- <Label Text="{Binding ValidateMessage, Mode=TwoWay}"></Label>
- </StackLayout>
- </ContentPage.Content>
- </ContentPage>
Open SignUpPage.xaml.cs and modify the content as below.
- using Xamarin.Forms;
-
- namespace FluentValidationDemo1
- {
- public partial class SignUpPage : ContentPage
- {
- SignUpPageViewModel uvm;
- public SignUpPage()
- {
- InitializeComponent();
- uvm = new SignUpPageViewModel();
- BindingContext = uvm;
- }
- }
- }
Note
Create a new project as I have attached only Portable project in this article.
Run the application. You will have the following output.
Click on "Submit" button without filling any field.
Fill the proper data on all the fields to make your validation successful.
The validation criteria are defined in UserValidator.cs file as -
- UserName - Length 10 to 20 and not null.
- Password - Not null.
- Confirm Password - Not null and equals Password.
- Email - not null and Email format.
You can check the same output on Android Emulator also.