Xamarin.Forms - Fluent Validation In MVVM

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Fluent Validation

Fluent Validation is one of the best Libraries for Xamarin.Forms, used to validate XAML Controls. Fluent Validation is used to create the validation logic separate from business logic. Fluent validation use lambda expressions for building validation rules for your business objects.

References

https://github.com/james-russo/XamarinForms-UnobtrusiveValidationPlugin

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Let's start.

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 

Xamarin.Forms - Fluent Validation In MVVM

Setup UI

Now, create a UI for your requirement. I just created a simple login page for validation purposes.

LoginPage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="XamarinApp.LoginPage">
    <ContentPage.Content>
        <StackLayout HorizontalOptions="Fill"  Margin="50,100" VerticalOptions="Start">
            <Label Text="Login" FontSize="Large"/>
            <Entry Placeholder="Username" Text="{Binding UserName}"/>
            <Entry Placeholder="Password" IsPassword="True" Text="{Binding Password}"/>
            <Label TextColor="Red" Text="{Binding LoginError}"/>
            <Button Text="Login" Command="{Binding LoginCommand}"/>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

LoginPageViewModel

Here, you can write your business logic for your requirement. I just added simple login validation only. LoginCommand will validate the login form.

LoginPageViewModel.cs

using System;
using System.ComponentModel;
using Xamarin.Forms;
using XamarinApp.Validations;

namespace XamarinApp.ViewModels
{
    public class LoginPageViewModel : INotifyPropertyChanged
    {
        #region Fields
        private string _username;
        private Command _LoginCommand;
        LoginValidation loginValidation;
        #endregion
        #region Constructor
        [Obsolete]
        public LoginPageViewModel()
        {
            loginValidation = new LoginValidation();
        }
        #endregion
        #region Properties
        public event PropertyChangedEventHandler PropertyChanged;
        public string UserName
        {
            get { return _username; }
            set
            {
                _username = value;
                OnPropertyChanged(nameof(UserName));
            }
        }
        public string Password { get; set; }
        public string LoginError { get; set; }

        public Command LoginCommand
        {
            get
            {
                return _LoginCommand ?? (_LoginCommand = new Command(ExecuteLoginCommand));
            }
        }
        #endregion
        #region Methods
        public void ExecuteLoginCommand()
        {
            
            var result = loginValidation.Validate(this);
            if (result.IsValid)
                LoginError = string.Empty;
        }
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion
    }
}

Install Fluent Validation NuGet

Install the following Nuget from Nuget Package Manager in your Visual Studio. Install Nuget only your .Net Standard or PCL Library.

Fluent Validation

Create Fluent Validator

Now, create a validator class in .Net Standard or PCL Library for your ViewModel or your business logic. I create LoginValidator for my LoginPageViewModel.

LoginValidation.cs

using System;
using FluentValidation;
using XamarinApp.ViewModels;

namespace XamarinApp.Validations
{
    public class LoginValidation: AbstractValidator<LoginPageViewModel>
    {
        public LoginValidation()
        {
            RuleFor(x => x.UserName).NotNull().OnFailure(x=>x.LoginError="Username or Password is Missing");
            RuleFor(x => x.Password).NotNull().OnFailure(x => x.LoginError = "Username or Password is Missing");
        }
    }
}

Here I just added the NotNull check validation with the failure message. You can explore more features for the Fluent validation.

Result

See the below screenshot when the Username and Password are null. The Validations failed.

Result 2

When username and password are NotNull the validation is Success.

Conclusion

I hope you have understood how to validate objects using fluent validation in MVVM in Xamarin.Forms App.

Thanks for reading. Please share your comments and feedback. Happy Coding :)


Similar Articles