Xamarin disable button & validating entries with behaviours

In my earlier post validate entries using behaviours I showed how I used Xamarin behaviours to show validation messages to the user. This is good, but it didn’t prevent the button from being pressed/submitted.

Here’s how I achieved this.

In my ViewModel add properties for the validators I use in the view

<br />
private EmailValidatorBehavior EmailValidatorBehavior;<br />
private RequiredEntryValidatorBehaviour RequiredEntryValidatorBehaviour;<br />

These need to be passed into the ViewModel, I used the constructor.

<br />
 public LoginViewModel(EmailValidatorBehavior emailValidatorBehavior, RequiredEntryValidatorBehaviour requiredEntryValidatorBehaviour)<br />
 {<br />
 EmailValidatorBehavior = emailValidatorBehavior;<br />
 RequiredEntryValidatorBehaviour = requiredEntryValidatorBehaviour;<br />
...<br />
}<br />

The validators are passed into the ViewModel, when the BindingContext is set

<br />
LoginViewModel viewModel;</p>
<p>public LoginPage ()<br />
{<br />
    InitializeComponent ();</p>
<p>    viewModel = new LoginViewModel(emailValidator, passwordValidator);<br />
    BindingContext = viewModel;<br />
}<br />

Then define a new property in the ViewModel to determine whether we’ve passed validation. This uses the IsValid properties of the behaviours

<br />
        public bool PassedValidation<br />
        {<br />
            get<br />
            {<br />
                return EmailValidatorBehavior.IsValid &amp;&amp; RequiredEntryValidatorBehaviour.IsValid;<br />
            }<br />
        }<br />

Bind to this property  in the IsEnabled attribute of the Button

<br />
&lt;Button Text=&quot;Login&quot; Command=&quot;{Binding LoginCommand}&quot; IsEnabled=&quot;{Binding PassedValidation}&quot; /&gt;<br />

Then when the email or password is changed in the ViewModel flag a change in the PassedValidation property, like so

<br />
        private string email;</p>
<p>        public string Email<br />
        {<br />
            get { return email; }<br />
            set<br />
            {<br />
                email = value;</p>
<p>                OnPropertyChanged(nameof(Email));<br />
                OnPropertyChanged(nameof(PassedValidation));<br />
            }<br />
        }<br />

Hope that makes sense!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.