How to Implement Xamarin Forms Validation
Tags: android, ios, csharp, beginners
Published: 2019-06-21 11:08:35

---
title: How to Implement Xamarin Forms Validation
published: true
description: This blog provides details about how to implement validation of the data in a Xamarin Forms application. This is portrayed using Syncfusion DataForm control
canonical_url: https://www.syncfusion.com/blogs/post/how-to-implement-xamarin-forms-validation.aspx
tags: android, ios, csharp, beginners
---
When a user interface enterprise application receives input, a common requirement will be to validate the provided information (such as email address, password, phone number). This is to ensure that, it satisfies the desired format and range for further processing. You can validate data in a user interface control by using built-in validations such as <a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2">INotifyDataErrorInfo</a> and data annotation while following the MVVM pattern.

In this blog, I will provide a walk-through on how to implement Xamarin Forms validation over data in the Syncfusion Xamarin.Forms <a href="https://www.syncfusion.com/xamarin-ui-controls/dataform">DataForm</a> control. Please go through the <a href="https://help.syncfusion.com/xamarin/sfdataform/getting-started">DataForm getting started</a> documentation before proceeding with this blog if you are new to the DataForm control.

A data form validates data and displays an error message in case of failure. This error message is shown at the bottom of the editor.
<h2>Built-in validations</h2>
We can validate fields in MVVM in the DataForm control using:
<ul>
 	<li>INotifyDataErrorInfo</li>
 	<li>Data annotation</li>
</ul>
<h3>INotifyDataErrorInfo</h3>
You can validate data by implementing the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2">INotifyDataErrorInfo</a> interface in the data object class. The below code example illustrates the same.
```csharp
public class EmployeeInfo: INotifyDataErrorInfo, INotifyPropertyChanged
{
    private int _EmployeeID;
    private string _Name;
    private string _Title;

    public event PropertyChangedEventHandler PropertyChanged;
    public event EventHandler ErrorsChanged;

    public EmployeeInfo()
    {

    }
    public int EmployeeID
    {
        get { return this._EmployeeID; }
        set
        {
            this._EmployeeID = value;
            this.RaisePropertyChanged("EmployeeID");
        }
    }
    public string Name
    {
        get { return this._Name; }
        set
        {
            this._Name = value;
            this.RaisePropertyChanged("Name");
        }
    }
    public string Title
    {
        get { return this._Title; }
        set
        {
            this._Title = value;
            this.RaisePropertyChanged("Title");
        }
    }

    [Display(AutoGenerateField = false)]
    public bool HasErrors
    {
        get
        {
            return false;
        }
    }
    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    public IEnumerable GetErrors(string propertyName)
    {
        var list = new List();
        if (!propertyName.Equals("Title"))
            return list;

        if (this.Title.Contains("Marketing"))
            list.Add("Marketing is not allowed");
        return list;
    }
}
```
<h3>Data annotations</h3>
The validation of the data fields using data annotation attributes is explained in the below topics.
<h4>Number validation</h4>
You can validate numeric types like int, double, and decimal properties using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.RangeAttribute.html">Range</a> attribute in numeric and numeric up-down editors.
```csharp
private int employeeID;
[Range(1000, 1500, ErrorMessage = "EmployeeID should be between 1000 and 1500")]
public int EmployeeID
{
    get { return this.employeeID; }
    set
    {
        this.employeeID = value;
        this.RaisePropertyChanged("EmployeeID");
    }
}
```
<h4>Phone number validation</h4>
You can validate the length of a phone number using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.StringLengthAttribute.html">StringLength</a> attribute.
```csharp
[StringLength(10, ErrorMessage = "Phone number should have 10 digits.")]
public string ContactNumber
{
    get { return this.contactNumber; }
    set
    {
        this.contactNumber = value;
        this.RaisePropertyChanged("ContactNumber");
        this.GetErrors("ContactNumber");
    }
}
```
As phone number format varies based on country, you can also use a regular expression and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2">INotifyDataErrorInfo</a> for validating it.
<h4>Mandatory fields validation</h4>
If any field in your application is mandatory, use the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.RequiredAttribute.html">Required</a> attribute to validate the data.
```csharp
private string name;

[Required(AllowEmptyStrings = false, ErrorMessage = "Name should not be empty")]
public string Name
{
    get { return this.name; }
    set
    {
        this.name = value;
        this.RaisePropertyChanged("Name");
    }
}
```
<h4>Email validation</h4>
You can validate an email ID using the <a href="https://help.syncfusion.com/cr/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.EmailAddressAttribute.html">EmailAddress</a> attribute.
```csharp
private string email;

[EmailAddress(ErrorMessage = "Please enter a valid e-mail id.")]
public string Email
{
    get { return this.email; }
    set
    {
        this.email = value;
        this.RaisePropertyChanged("Email");
        this.GetErrors("Email");
    }
}
```
<h4>Password validation</h4>
To validate a new password entered in a form, you can use a regular expression and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2">INotifyDataErrorInfo</a>.
```csharp
private Regex passwordRegExp = new Regex("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})");

private string password;
[DataType(DataType.Password)]
public string Password
{
    get { return this.password; }
    set
    {
        this.password = value;
        this.RaisePropertyChanged("Password");
    }
}

public IEnumerable GetErrors(string propertyName)
{
    var list = new List();
    if (!propertyName.Equals("Password"))
        return list;

    if (!this.passwordRegExp.IsMatch(this.Password))
    {
        list.Add("Password must contain at least one digit, one uppercase character and one special symbol");
    }
    return list;
}
```
<h4>String length validation</h4>
You can validate the length of any property value in the text editor using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.StringLengthAttribute.html">StringLength</a> attribute.
```csharp
private string name;

[Required(AllowEmptyStrings = false, ErrorMessage = "Name should not be empty")]
[StringLength(10, ErrorMessage = "Name should not exceed 10 characters")]
public string Name
{
    get { return this.name; }
    set
    {
        this.name = value;
        this.RaisePropertyChanged("Name");
    }
}
```
You can also specify, the minimum and maximum character length for the string property.
```csharp
private string title;
[MinLength(5, ErrorMessage = "Title should be at least 5 characters.")]
[MaxLength(15, ErrorMessage = "Title should not exceed 15 characters.")]
public string Title
{
    get { return this.title; }
    set
    {
        this.title = value;
        this.RaisePropertyChanged("Title");
    }
}
```
<h4>Date range validation</h4>
To check a date range in the date editor, you need to specify the minimum and maximum date range by using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.RangeAttribute.html">DateRange attribute</a>.
```csharp
private DateTime joinedDate;
[DateRange(MinYear = 2010, MaxYear = 2017, ErrorMessage = "Joined date is invalid")]
public DateTime JoinedDate
{
    get
    {
        return joinedDate;
    }
    set
    {
        joinedDate = value;
    }
}
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Date-Range-Xamarin-Forms-Validation.png" alt="Date Range Xamarin Forms Validation" style="width:100%">
  <figcaption>Date Range Xamarin Forms Validation</figcaption>
</figure>
The following attributes are also available in data forms to validate fields.

<a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.EmailAddressAttribute.html">EmailAddressAttribute</a>

<a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.MaxLengthAttribute.html">MaxLengthAttribute</a>

<a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.MinLengthAttribute.html">MinLengthAttribute</a>
<h2>Validation mode</h2>
The <a href="http://help.syncfusion.com/cr/cref_files/xamarin-android/Syncfusion.SfDataForm.Android~Syncfusion.Android.DataForm.SfDataForm~ValidationMode.html">ValidationMode</a> determines when the value should be validated. The supported validation modes are:
<ul>
 	<li><strong>LostFocus</strong>—Value validation occurs when the editor is out of focus.</li>
 	<li><strong>PropertyChanged</strong>—Value validation occurs immediately whenever it is changed.</li>
 	<li><strong>Explicit</strong>—Value is validated manually by calling the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.SfDataForm~Validate().html">Validate</a> or <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.SfDataForm~Validate(String).html">SfDataForm.Validate (propertyName)</a> methods.</li>
</ul>
<strong>Explicit mode</strong>

The Explicit mode of validation refers to performing validation process irrespective of the state of the element, ie., it is performed at any time, as per the requirement. You can validate the values of all properties in a data object by using the following code.
```csharp
bool isValid = dataForm.Validate();
```
To validate the value of a specific property, pass the property name as argument.
```csharp
bool isPropertyValid = dataForm.Validate("PropertyName");
```
<h2>Custom validation through events</h2>
You can also validate the data entered in the form using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.SfDataForm~Validating_EV.html">Validating</a> event of DataForm.
```csharp
dataForm.Validating += DataForm_Validating;
private void DataForm_Validating(object sender, ValidatingEventArgs e)
{
    if (e.PropertyName == "Name")
    {
        if (e.Value != null &amp;&amp; e.Value.ToString().Length &gt; 8)
        {
            e.IsValid = false;
            e.ErrorMessage = "Name should not exceed 8 characters";
        }
    }
}
```
You can validate the data using <a href="https://fluentvalidation.net/start">fluent validation</a> with this event.

You can receive a notification after completing a validation using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.SfDataForm~Validated_EV.html">Validated</a> event of the data form.
```csharp
dataForm.Validated += DataForm_Validated;
private void DataForm_Validated(object sender, ValidatedEventArgs e)
{
    var isValid = e.IsValid;
    var propertyName = e.PropertyName;
}
```
<h2>Valid or positive message</h2>
If the value meets the desired criteria, you can show a valid or positive message. Like an error message, the valid message will also be displayed at the bottom of the editor.
```csharp
private string name;
[DisplayOptions(ValidMessage = "Name length is enough")]
[StringLength(10, ErrorMessage = "Name should not exceed 10 characters")]
public string Name
{
    get { return this.name; }
    set
    {
        this.name = value;
        this.RaisePropertyChanged("Name");
    }
}
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Valid-message-Xamarin-Forms-Validation.png" alt="Valid message - Xamarin Forms Validation" style="width:100%">
  <figcaption>Valid message - Xamarin Forms Validation</figcaption>
</figure>
You can validate the values of all editors, such as entry, numeric, check box, picker, date, or time.
<h2>Validation label customization</h2>
You can customize the default view of the validation label by using the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.SfDataForm~ValidationTemplate.html">ValidationTemplate</a> property of the DataForm control. It lets you choose a different data template for each validation message, customizing the appearance of a validation message based on certain conditions.
```xml
<ContentPage.Resources>
    <ResourceDictionary>
        <local:TemplateSelector x:Key="validationDataTemplateSelector" />
    </ResourceDictionary>
</ContentPage.Resources>

<dataForm:SfDataForm Grid.Row="1" x:Name="dataForm" ValidationTemplate="{StaticResource validationDataTemplateSelector}" />
```
<h4>Creating different templates for validation messages</h4>
The following code shows different templates for each field.
```xml
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DataForm_Validation.ValidMessageTemplate" 
    VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <Grid BackgroundColor="Transparent">
        <Button x:Name="maingrid"  CornerRadius="8"  Text="Name length is enough" FontSize="9" TextColor="Green" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"/>
   </Grid>
</Grid>
```

```xml
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DataForm_Validation.InValidMessageTemplate"
    VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <Grid BackgroundColor="Transparent">
        <Button x:Name="maingrid"  CornerRadius="8" Text="Please enter your first name" FontSize="9" TextColor="White" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"/>
  </Grid>
</Grid>
```
<h4>Choose different templates based on conditions</h4>
In the DataTemplateSelector, you can return the desired template conditionally based on the <a href="https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfDataForm.XForms~Syncfusion.XForms.DataForm.DataFormItem.html">DataFormItem</a>.
```csharp
public class TemplateSelector : DataTemplateSelector
{
    public DataTemplate ValidMessageTemplate { get; set; }
    public DataTemplate InvalidMessageTemplate { get; set; }     
    public DataTemplate LastNameTemplate { get; set; }
    public DataTemplate EmailTemplate { get; set; }
    public DataTemplate ContactNumberTemplate { get; set; }

    public TemplateSelector()
    {
        ValidMessageTemplate = new DataTemplate(typeof(ValidMessageTemplate));
        InvalidMessageTemplate = new DataTemplate(typeof(InValidMessageTemplate));
        EmailTemplate = new DataTemplate(typeof(EmailTemplate));
        ContactNumberTemplate = new DataTemplate(typeof(ContactNumberTemplate));
    }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        var dataform = (container as SfDataForm);
        if (dataform == null) return null;
        if (dataform != null)
        {
            if ((item as DataFormItem).LabelText == "First Name")
            {
                if (!(item as DataFormItem).IsValid)
                {
                    return InvalidMessageTemplate;
                }
                else
                {
                    return ValidMessageTemplate;
                }
            }
            else if ((item as DataFormItem).LabelText == "Email")
            {
                if (!(item as DataFormItem).IsValid)
                {
                    return EmailTemplate;
                }
            }
            else if ((item as DataFormItem).LabelText == "Contact Number")
            {
                if (!(item as DataFormItem).IsValid)
                {
                    return ContactNumberTemplate;
                }
            }
            return null;
        }
        else
            return null;
       
    }    
}
```
The following screenshot shows the validation message customization done using the above code.
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Customized-valid-template.png" alt="Customized valid template" style="width:100%">
  <figcaption>Customized valid template</figcaption>
</figure>
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Customized-invalid-template.png" alt="Customized invalid template" style="width:100%">
  <figcaption>Customized invalid template</figcaption>
</figure>

<h2>Conclusion</h2>
In this blog post, we saw how to validate data in the Syncfusion <a href="https://www.syncfusion.com/products/xamarin/data-form">DataForm</a> control. The sample for this is available in this <a href="https://github.com/SyncfusionExamples/dataform-validatation">GitHub location</a>. Please feel free to try out this sample and provide your feedback or questions in the comments section. You can explore other features of the DataForm control in our <a href="https://help.syncfusion.com/xamarin/sfdataform/getting-started">documentation</a>.

If you have any questions or require clarification about these features, please let us know in the comments below. You can also contact us through our <a href="https://www.syncfusion.com/forums">support forum</a>, <a href="https://www.syncfusion.com/support/directtrac/">Direct-Trac</a>, or <a href="https://www.syncfusion.com/feedback/">Feedback Portal</a>. We are happy to assist you!

The post [How to Implement Xamarin Forms Validation](https://www.syncfusion.com/blogs/post/how-to-implement-xamarin-forms-validation.aspx) first appeared on [Syncfusion Blogs](https://www.syncfusion.com/blogs).