Validation Rules for Email in Xamarin Forms

Table of Contents

Learn how to apply validation rules to emails in our forms in Xamarin.Forms. The best, and fastest, the way is to use the Plugin.ValidationRules library.

Many people don’t even know the concept of what validation rules are, and if you’re one of them I recommend you watch all the content I’ve developed for you. It saves you a lot of time in your day-to-day as a developer.

This is the beginning of a small series that I call “Tips and Tricks with Plugin.ValidationRules” where I will teach you how to get the most out of this library so that you do not have headaches doing validations in your forms.

Validating the email

The first thing we have to know is that with the new version of the Plugin.ValidationRules we have a builder that we can use to initialize our properties very easily.

...
            public Validatable<string> Email { get; set; }
...
            Email = Validator.Build<string>()
                    .IsRequired("An email is required.")
                    .WithRule(new EmailRule(), "Email is not valid.")
                    .When(x => Name.Validate() && LastName.Validate());
...
  • Notice that we are using Validator.Build<string>() to initialize our property.
  • We use the extension .IsRequired() to add a non-null or empty validation rule.
  • With the extension .WithRule() we added our validation rule for email EmailRule() .
  • Similarly, we are using the extension .When() to validate our email only when the First and Last Name are valid (we also validate these fields to make a single validation call, but here you can use your logic or delete this line of code).

In our XAML we can have something similar to this to link the validations.

...
           <Entry Placeholder="Email" Text="{Binding Email.Value}" />
           <Label  Text="{Binding Email.Error}" TextColor="Red" />
...

With this, we would have the validations working for us. Tell me if it’s not really crazy.

You can see all the code here.

Conclusions

Nothing enjoy. If you want more tips like these let me know in the comments or on my Twitter, I am being very active there.

Remember that your interactions are what help me know where to direct content. In the end, the idea is to help as much as we can.

I hope you find this video useful. A hug, and until next time.

Share this content!

Facebook
Twitter
LinkedIn
Telegram
WhatsApp