Create and Validate a Sign-Up Form in .NET MAUI
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)

Create and Validate a Sign-Up Form in .NET MAUI

A sign-up form allows users to create an account in an application by providing details such as name, email address, and password. Usually, such a form is used for registration or membership subscription.

The Syncfusion .NET MAUI DataForm allows developers to create data entry forms. This control also supports validating user input. By validating the input, users will be prompted to provide only correct values into the form, maintaining the integrity and consistency of the data stored in the database to prevent errors, inconsistencies, and security threats.

In this article, we’ll see how to create a sign-up form and validate the data entered using the Syncfusion .NET MAUI DataForm control.

Note: Refer to the .NET MAUI DataForm documentation before getting started.

Creating a sign-up form using the .NET MAUI DataForm control

First, create a sign-up form using the .NET MAUI DataForm control.

Initialize the .NET MAUI DataForm control

Follow these steps to initialize the .NET MAUI DataForm control:

  1. Create a new .NET MAUI application in Visual Studio.
  2. Syncfusion .NET MAUI components are available in the NuGet Gallery. To add the DataForm to your project, open the NuGet package manager in Visual Studio, search for Syncfusion.Maui.DataForm, and then install it.
  3. Import the control’s namespace Syncfusion.Maui.DataForm in the XAML or C# code.
  4. Initialize the SfDataForm control in the XAML page.
    <ContentPage>
      …..
      xmlns:dataForm="clr-namespace:Syncfusion.Maui.DataForm;assembly=Syncfusion.Maui.DataForm"
      …..
     <dataForm:SfDataForm/>
    </ContentPage>
  5. The NuGet package Syncfusion.Maui.Core is a dependent package for all Syncfusion .NET MAUI controls. In the MauiProgram.cs file, register the handler for the Syncfusion core assembly.
    builder.ConfigureSyncfusionCore()

Create the data form model

Let’s create the data form model for the sign-up form. This consists of fields to store specific information such as names, addresses, phone numbers, and more. You can also add attributes to the data model class properties for efficient data handling.

Refer to the following code example.

public class SignUpFormModel
{ 
   [Display(Prompt = "Enter your first name", Name = "First name")]
   public string FirstName { get; set; }
 
   [Display(Prompt = "Enter your last name", Name = "Last name")]
   public string LastName { get; set; }
 
   [Display(Prompt = "Enter your email", Name = "Email")]
   public string Email { get; set; }
 
   [Display(Prompt = "Enter your mobile number", Name = "Mobile number")]
   public double? MobileNumber { get; set; }
 
   [Display(Prompt = "Enter your password", Name = "Password")]
   public string Password { get; set; }
 
   [Display(Prompt = "Confirm password", Name = "Re-enter Password")]
   [DataType(DataType.Password)]
   public string RetypePassword { get; set; }
 
   [DataType(DataType.MultilineText)]
   [Display(Prompt = "Enter your address", Name = "Address")]
   public string Address { get; set; }
 
   [Display(Prompt = "Enter your city", Name = "City")]
   public string City { get; set; }
 
   [Display(Prompt = "Enter your state", Name = "State")]
   public string State { get; set; }
 
   [Display(Prompt = "Enter your country", Name = "Country")]
   public string Country { get; set; }
 
   [Display(Prompt = "Enter zip code", Name = "Zip code")]
   public double? ZipCode { get; set; }
}

Create the sign-up form with editors

By default, the data form auto generates the data editors based on the primitive data types such as string, enumeration, DateTime, and TimeSpan in the DataObject property.

The .NET MAUI DataForm supports built-in editors such as text, password, multiline, combo box, autocomplete, date, time, checkbox, switch, and radio group.

Refer to the following code example. In it, we set the data form model (SignUpFormViewModel) to the DataObject property to create the data editors for the sign-up form.

XAML

<Grid.BindingContext>
   <local:SignUpFormViewModel/>
</Grid.BindingContext>
<dataForm:SfDataForm x:Name="signUpForm" DataObject="{Binding SignUpFormModel}"/>

C#

public class SignUpFormViewModel
{
    /// <summary>
    /// Initializes a new instance of the <see cref=" SignUpFormViewModel " /> class.
    /// </summary>
    public SignUpFormViewModel()
    {
       this.SignUpFormModel = new SignUpFormModel();
    }
 
    /// <summary>
    /// Gets or sets the sign-up model.
    /// </summary>
    public SignUpFormModel SignUpFormModel { get; set; }
 
}
Sign-Up Form Created Using .NET MAUI DataForm Control
Sign-Up Form Created Using .NET MAUI DataForm Control

Validating the data in the sign-up form using the .NET MAUI DataForm control

We have created the sign-up form. Let’s proceed with the validation processes.

Validate the data using the validation attributes

The .NET MAUI DataForm control provides the attributes to handle data validation. In our example, we’ll add the following validation checks to our sign-up form:

  • Required fields validation: Ensures that all required fields, such as name, email, and password, are filled out before submitting the form.
  • Email validation: Checks whether the email data is in the correct format. The email data should include the @ character (e.g., example@domain.com).
  • Password strength validation: Ensures that the provided password satisfies certain criteria, such as minimum length and the inclusion of special characters.
  • Confirm password validation: Ensures that the confirmed password matches the provided password.
  • Phone number validation: Ensures that the phone number provided is valid and is in the correct format.

Refer to the following code example.

[Display(Prompt = "Enter your first name", Name = "First name")]
[Required(ErrorMessage = "Please enter your first name")]
[StringLength(20, ErrorMessage = "First name should not exceed 20 characters")]
public string FirstName { get; set; }
 
[Display(Prompt = "Enter your last name", Name = "Last name")]
[Required(ErrorMessage = "Please enter your last name")]
[StringLength(20, ErrorMessage = "First name should not exceed 20 characters")]
public string LastName { get; set; }
 
[Display(Prompt = "Enter your email", Name = "Email")]
[EmailAddress(ErrorMessage = "Please enter your email")]
public string Email { get; set; }
 
[Display(Prompt = "Enter your mobile number", Name = "Mobile number")]
[StringLength(10, MinimumLength = 6, ErrorMessage = "Please enter a valid number")]
public double? MobileNumber { get; set; }
 
[Display(Prompt = "Enter your password", Name = "Password")]
[DataType(DataType.Password)]
[DataFormDisplayOptions(ColumnSpan = 2, ValidMessage = "Password strength is good")]
[Required(ErrorMessage = "Please enter the password")]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,}$", ErrorMessage = "A minimum 8-character password should contain a combination of uppercase and lowercase letters.")]
public string Password { get; set; }
 
[Display(Prompt = "Confirm password", Name = "Re-enter Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Please enter the password")]
public string RetypePassword { get; set; }
 
[DataType(DataType.MultilineText)]
[Display(Prompt = "Enter your address", Name = "Address")]
[Required(ErrorMessage = "Please enter your address")]
public string Address { get; set; }
 
[Display(Prompt = "Enter your city", Name = "City")]
[Required(ErrorMessage = "Please enter your city")]
public string City { get; set; }
 
[Display(Prompt = "Enter your state", Name = "State")]
[Required(ErrorMessage = "Please enter your state")]
public string State { get; set; }
 
[Display(Prompt = "Enter your country", Name = "Country")]
public string Country { get; set; }
 
[Display(Prompt = "Enter zip code", Name = "Zip code")]
[Required(ErrorMessage = "Please enter your zip code")]
public double? ZipCode { get; set; }
Validating the Sign-Up Form Using Validation Attributes
Validating the Sign-Up Form Using Validation Attributes

Show validation success message

If the input values are correct, show the successful validation message. This will show the users that their provided data is in the required format.

Refer to the following code example. Here, we will display the valid message Password strength is good at the bottom of the Password field upon successful validation.

[Display(Prompt = “Enter your password”, Name = “Password”)]
[DataType(DataType.Password)]
[DataFormDisplayOptions(ColumnSpan = 2, ValidMessage = “Password strength is good”)]
[Required(ErrorMessage = “Please enter the password”)]
[RegularExpression(@”^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,}$”, ErrorMessage = “A minimum 8-character password should contain a combination of uppercase and lowercase letters.”)]
public string Password { get; set; }
Displaying Validation Success Message in the Sign-Up Form
Displaying Validation Success Message in the Sign-Up Form

Set validate modes in the DataForm

The .NET MAUI DataForm control supports the following validation modes to denote when the value should be validated:

  • LostFocus: This is the default validation mode, and the input value will be validated when the editor loses focus.
  • PropertyChanged: The input value will be validated immediately when it is changed.
  • Manual: Use this mode to manually validate the values by calling the Validate method.

Refer to the following code example. Here, we have set the validation mode as PropertyChanged.

<dataForm:SfDataForm x:Name="signUpForm"
                   DataObject="{Binding SignUpFormModel}"
                   ValidationMode="PropertyChanged"
                   CommitMode="PropertyChanged"/>
Validate the Data on Property Change in the Sign-Up Form
Validate the Data on Property Change in the Sign-Up Form

Validate the data using IDataErrorInfo

We can implement the IDataErrorInfo interface in the data object class to validate the sign-up form.

Refer to the following code example. Here, we implement the IDataErrorInfo validation in the RetypePassword field.

public class SignUpFormModel : IDataErrorInfo
{
   [Display(Prompt = "Enter your password", Name = "Password")]
   [DataType(DataType.Password)]
   [DataFormDisplayOptions(ColumnSpan = 2, ValidMessage = "Password strength is good")]
   [Required(ErrorMessage = "Please enter the password")]
   [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,}$", ErrorMessage = "A minimum 8-character password should contain a combination of uppercase and lowercase letters.")]
   public string Password { get; set; }
 
   [Display(Prompt = "Confirm password", Name = "Re-enter Password")]
   [DataType(DataType.Password)]
   [Required(ErrorMessage = "Please enter the password")]
   [DataFormDisplayOptions(ColumnSpan = 2)]
   public string RetypePassword { get; set; }
    
   [Display(AutoGenerateField = false)]
   public string Error
   {
      get
      {
         return string.Empty;
      }
    }
 
    [Display(AutoGenerateField = false)]
    public string this[string name]
    {
       get
       {
          string result = string.Empty;
          if (name == nameof(RetypePassword) && this.Password != this.RetypePassword)
           {
              result = string.IsNullOrEmpty(this.RetypePassword) ? string.Empty : "The passwords do not match";
            }
 
            return result;
       }
    }
}
Validating the Sign-Up Form Field Using IDataErrorInfo Interface
Validating the Sign-Up Form Field Using IDataErrorInfo Interface

Validate the data using INotifyDataErrorInfo

You can also validate the data by implementing the INotifyDataErrorInfo interface in the data object class.

Refer to the following code example. Here we implemented INotifyDataErrorInfo validation in the Country field.

public class SignUpFormModel : INotifyDataErrorInfo
{
 
   [Display(Prompt = "Enter your country", Name = "Country")]
   public string Country { get; set; }
 
   [Display(AutoGenerateField = false)]
   public bool HasErrors
   {
      get
      {
         return false;
      }
    }
 
    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
 
    [Display(AutoGenerateField = false)]
    public IEnumerable GetErrors(string propertyName)
    {
        var list = new List<string>();
        if (propertyName.Equals("Country") && string.IsNullOrEmpty(this.Country))
            list.Add("Please select your country");
        return list;
     }
 
}
Validating the Sign-Up Form Using INotifyDataErrorInfo Interface
Validating the Sign-Up Form Using INotifyDataErrorInfo Interface

Validate the form before signing up

Finally, we’ll validate the complete form when the Sign-up button is clicked by using the Validate method.

Refer to the following code example.

private async void OnSignUpButtonClicked(object? sender, EventArgs e)
{
   if (this.dataForm != null && App.Current?.MainPage != null)
   {
      if (this.dataForm.Validate())
      {
         await App.Current.MainPage.DisplayAlert("", "Signed up successfully", "OK");
      }
      else
      {
          await App.Current.MainPage.DisplayAlert("", "Please enter the required details", "OK");
      }
   }
}

After executing the previous code example, we will get the output shown in the following images.

Validating the Entire Sign-Up Form Before Submitting
Validating the Entire Sign-Up Form Before Submitting
Sign-Up Form Showing Validation Messages
Sign-Up Form Showing Validation Messages

GitHub reference

Check out the complete code example to create and validate a sign-up form using the .NET MAUI DataForm on GitHub.

Supercharge your cross-platform apps with Syncfusion's robust .NET MAUI controls.

Conclusion

Thanks for reading! In this blog, we have learned how to create and validate a sign-up form using the .NET MAUI DataForm control. Try out the steps in this blog and leave your feedback in the comments section below.

For current Syncfusion customers, the newest version of Essential Studio is available from the license and downloads page. If you are not a customer, try our 30-day free trial to check out these new features.

You can also contact us through our support forums, feedback, or support portal. We are always happy to assist you!

Test Flight
App Center Badge
Google Play Store Badge
Microsoft Badge
Github Store Badge

Related blogs

Tags:

Share this post:

Comments (2)

Is there a way to assign values to data form fields either from the code-behind or view model since 2-way data binding is not available on MAUI DataForm, and NotifyPropertyChanges=”True” is also missing? Are there any workarounds for this? I need to set default or predefined values on certain fields depending on specific conditions.

Hi Gumdev11,

 Your requirement of assigning value to the editor can be achieved by setting the default value for the model property to display the value in the editors. Please refer to the following code snippet for your reference.

Code Snippet
public DataFormViewModel()
{
   this.ContactInfo = new ContactInfo();
   this.ContactInfo.FirstName = “John”;
   this.ContactInfo.LastName = “Wick”;
}

 As of now, the data form will automatically update the data object value when we changed the value in the editor view. For the dynamic model change, we suggest you use the property changed event for the data object to update the editor. Please refer to the following code snippet for your reference.

 Code Snippet
public MainPage()
{
   InitializeComponent();
   (dataForm.DataObject as ContactInfo).PropertyChanged += MainPage_PropertyChanged;
}

private void MainPage_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
   if (!string.IsNullOrEmpty(e.PropertyName))
   {
        dataForm.UpdateEditor(e.PropertyName);
   }
}

 Please let us know if you have any concerns.

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed