Validation Rules for Email in Xamarin Forms

Contenido

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.

Similarly, the Plugin.ValidationRules library has a validation rule for mail that you can use, or you can create your own.

...
            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.

What do you think of this content?
 
Luis Matos

Luis Matos

I help professionals and companies to create value solutions. I am a Systems Engineer, blockchain executive, and international mobile application speaker. Founder of the Malla Consulting Agency and several international technology communities.
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x

Search in the site