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

private EmailValidatorBehavior EmailValidatorBehavior;
private RequiredEntryValidatorBehaviour RequiredEntryValidatorBehaviour;

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

 public LoginViewModel(EmailValidatorBehavior emailValidatorBehavior, RequiredEntryValidatorBehaviour requiredEntryValidatorBehaviour)
 {
 EmailValidatorBehavior = emailValidatorBehavior;
 RequiredEntryValidatorBehaviour = requiredEntryValidatorBehaviour;
...
}

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

LoginViewModel viewModel;

public LoginPage ()
{
    InitializeComponent ();

    viewModel = new LoginViewModel(emailValidator, passwordValidator);
    BindingContext = viewModel;
}

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

        public bool PassedValidation
        {
            get
            {
                return EmailValidatorBehavior.IsValid && RequiredEntryValidatorBehaviour.IsValid;
            }
        }

Bind to this property  in the IsEnabled attribute of the Button

<Button Text="Login" Command="{Binding LoginCommand}" IsEnabled="{Binding PassedValidation}" />

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

        private string email;

        public string Email
        {
            get { return email; }
            set
            {
                email = value;

                OnPropertyChanged(nameof(Email));
                OnPropertyChanged(nameof(PassedValidation));
            }
        }

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.