Fluent Validation With MVVM In Xamarin Forms Application

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.

Fluent validation with MVVM

Select project type and give this project a name.

Fluent validation with MVVM

Select the template as Blank App and code sharing as PCL.

Fluent validation with MVVM

Set the target and minimum platform versions that your application will support.

Fluent validation with MVVM

Set the below configuration.

Fluent validation with MVVM

Open "Manage NuGet packages for Solutions" and install the following components.

Fluent validation with MVVM

Fluent validation with MVVM

The ViewModel directory will be added. This contains two files - MainViewModel.cs and ViewModelLocator.cs.

Create the Models folder and add the following files.

  1. Create file cs.
    1. namespace FluentValidationDemo1.Models  
    2. {  
    3.     public class User  
    4.     {  
    5.         public string UserName { get; set; }  
    6.         public string Password { get; set; }  
    7.         public string ConfirmPassword { get; set; }  
    8.         public string Email { get; set; }  
    9.     }  
    10. }  

  1. Create file cs.
    1. using FluentValidation;  
    2.   
    3. namespace FluentValidationDemo1.Models  
    4. {  
    5.     [FluentValidation.Attributes.Validator(typeof(UserValidator))]  
    6.     public class UserValidator : AbstractValidator<User>  
    7.     {  
    8.         public UserValidator()  
    9.         {  
    10.             RuleFor(x => x.UserName).NotNull().Length(10, 20);  
    11.             RuleFor(x => x.Password).NotNull();  
    12.             RuleFor(x => x.ConfirmPassword).NotNull().Equal(x => x.Password);  
    13.             RuleFor(x => x.Email).NotNull().EmailAddress();  
    14.         }  
    15.     }  
    16. }  

We have to define the validation attributes for the class you want to validate.

Inside ViewModel folder, create a file named SignUpPageViewModel.cs.

  1. using FluentValidation;  
  2. using Xamarin.Forms;  
  3. using FluentValidationDemo1.Models;  
  4. using GalaSoft.MvvmLight;  
  5.   
  6. namespace FluentValidationDemo1.ViewModel  
  7. {  
  8.     public class SignUpPageViewModel : ViewModelBase  
  9.     {  
  10.         public User UserObj { get; set; }  
  11.   
  12.         private string _username;  
  13.         public string UserName  
  14.         {  
  15.             get  
  16.             {  
  17.                 return _username;  
  18.             }  
  19.             set  
  20.             {  
  21.                 this.Set(ref this._username, value, "UserName");  
  22.             }  
  23.         }  
  24.   
  25.         private string _password;  
  26.         public string Password  
  27.         {  
  28.             get  
  29.             {  
  30.                 return _password;  
  31.             }  
  32.             set  
  33.             {  
  34.                 this.Set(ref this._password, value, "Password");  
  35.             }  
  36.         }  
  37.         private string _confirmPassword;  
  38.         public string ConfirmPassword  
  39.         {  
  40.             get  
  41.             {  
  42.                 return _confirmPassword;  
  43.             }  
  44.             set  
  45.             {  
  46.                 this.Set(ref this._confirmPassword, value, "ConfirmPassword");  
  47.             }  
  48.         }  
  49.         private string _email;  
  50.         public string Email  
  51.         {  
  52.             get  
  53.             {  
  54.                 return _email;  
  55.             }  
  56.             set  
  57.             {  
  58.                 this.Set(ref this._email, value, "Email");  
  59.             }  
  60.         }  
  61.   
  62.         private readonly IValidator _validator;  
  63.         public SignUpPageViewModel()  
  64.         {  
  65.             _validator = new UserValidator();  
  66.         }  
  67.         private Command signUpCommand;  
  68.         public Command SignUpCommand  
  69.         {  
  70.             get  
  71.             {  
  72.                 return signUpCommand ?? (signUpCommand = new Command(ExecuteSignUpCommand));  
  73.             }  
  74.         }  
  75.         private string _validateMessage;  
  76.         public string ValidateMessage  
  77.         {  
  78.             get  
  79.             {  
  80.                 return _validateMessage;  
  81.             }  
  82.             set  
  83.             {  
  84.                 this.Set(ref this._validateMessage, value, "ValidateMessage");  
  85.             }  
  86.         }  
  87.         protected void ExecuteSignUpCommand()  
  88.         {  
  89.             UserObj = new User  
  90.             {  
  91.                 UserName = _username,  
  92.                 Password = _password,  
  93.                 ConfirmPassword = _confirmPassword,  
  94.                 Email = _email  
  95.             };  
  96.             var validationResult = _validator.Validate(UserObj);  
  97.             if (validationResult.IsValid)  
  98.             {  
  99.                 ValidateMessage = "Validation Success..!!";  
  100.             }  
  101.             else  
  102.             {  
  103.                 ValidateMessage = "Validation Failes..!!";  
  104.             }  
  105.         }  
  106.     }  
  107. }  

Rename the file MainPage.xaml.cs to SignUpPage.xaml.cs. Open App.xaml.cs and change the below constructor code.


Fluent validation with MVVM

The directory structure will be as follow.

Fluent validation with MVVM

Open SignUpPage.xaml from Portable project and modify the content as below.

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:FluentValidationDemo1"  
  5.              xmlns:val="clr-namespace:FluentValidationDemo1;assembly=FluentValidationDemo1"  
  6.              xmlns:vm="clr-namespace:FluentValidationDemo1.ViewModel; assembly=FluentValidationDemo1"  
  7.              x:Class="FluentValidationDemo1.SignUpPage" BackgroundColor="Cyan">  
  8.     <ContentPage.Content>  
  9.         <StackLayout>  
  10.             <StackLayout.BindingContext>  
  11.                 <vm:SignUpPageViewModel />  
  12.             </StackLayout.BindingContext>  
  13.             <Label Text="UserName" />  
  14.             <Entry Text="{Binding UserName}"></Entry>  
  15.             <Label Text="Password" />  
  16.             <Entry IsPassword="True" Text="{Binding Password}"></Entry>  
  17.             <Label Text="Confirm Password"></Label>  
  18.             <Entry IsPassword="True" Text="{Binding ConfirmPassword}"></Entry>  
  19.             <Label Text="Email"></Label>  
  20.             <Entry Text="{Binding Email}"></Entry>  
  21.             <Button Text="Submit" Command="{Binding SignUpCommand}"></Button>  
  22.             <Label Text="{Binding ValidateMessage, Mode=TwoWay}"></Label>  
  23.         </StackLayout>  
  24.     </ContentPage.Content>  
  25. </ContentPage>  

Open SignUpPage.xaml.cs and modify the content as below.

  1. using Xamarin.Forms;  
  2.   
  3. namespace FluentValidationDemo1  
  4. {  
  5.     public partial class SignUpPage : ContentPage  
  6.     {  
  7.         SignUpPageViewModel uvm;  
  8.         public SignUpPage()  
  9.         {  
  10.             InitializeComponent();  
  11.             uvm = new SignUpPageViewModel();  
  12.             BindingContext = uvm;  
  13.         }  
  14.     }  
  15. }  

Note
Create a new project as I have attached only Portable project in this article.

Run the application. You will have the following output.


Fluent validation with MVVM

Click on "Submit" button without filling any field.

Fluent validation with MVVM

Fill the proper data on all the fields to make your validation successful.

Fluent validation with MVVM

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.

Up Next
    Ebook Download
    View all
    Learn
    View all