Building a data form with validation in 3 minutes using AOP





0/5 (0 vote)
Building a data form with validation in 3 minutes using xamarin and postsharp. Having a data form is very common in modern mobile applications , and of course in most cases you will need to validate user input before allowing him to submit the form..
Building a data form with validation in 3 minutes using xamarin and postsharp

Having a data form is very common in modern mobile applications , and of course in most cases you will need to validate user input before allowing him to submit the form.
In this article i will present a declarative and clean way to do the job in less then 3 minutes.
We will use syncfusion xamarin forms dataform control or any INotifyDataErrorInfo compatible data form control and Postsharp for AOP
lets start by installing postsharp visual studio extension and then create a normal xamarin forms project and install these nuget packages in the shared project:
Xamarin.Aspects.Patterns.Data.Validation 1.0.0
and
now we are ready lets create our model class
public class User { public string Email { get; set; } public string Paswword { get; set; } public string ConfirmPassword { get; set; } }
and the validator class
public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(u => u.Email).EmailAddress(); RuleFor(u => u.Paswword).MinimumLength(6); RuleFor(u => u.ConfirmPassword).Matches(u => u.Paswword); } }
add the NotifyDataErrorInfo
Attribute to the user class
[NotifyDataErrorInfo(typeof(UserValidator))] public class User { public string Email { get; set; } public string Paswword { get; set; } public string ConfirmPassword { get; set; } }
and now simply create a User object in your viewmodel and bind to the data from control as described here https://help.syncfusion.com/xamarin/sfdataform/getting-started
<?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:GettingStarted" xmlns:dataForm="clr-namespace:Syncfusion.XForms.DataForm;assembly=Syncfusion.SfDataForm.XForms" x:Class="GettingStarted.MainPage"> <ContentPage.BindingContext> <local:ViewModel/> </ContentPage.BindingContext> <dataForm:SfDataForm x:Name="dataForm" DataObject="{Binding User}"/> </ContentPage>
and we are done.