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

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

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. namespace FluentValidationDemo1
  3. {
  4. public partial class SignUpPage : ContentPage
  5. {
  6. SignUpPageViewModel uvm;
  7. public SignUpPage()
  8. {
  9. InitializeComponent();
  10. uvm = new SignUpPageViewModel();
  11. BindingContext = uvm;
  12. }
  13. }
  14. }

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 -

You can check the same output on Android Emulator also.