MVVM - Validate Form and DisplayAlert

reconrecon USMember ✭✭

I am using MVVM to validate my form. How do I use a popup to notify the user that a field needs to be displayed?

PAGE
`
public class ConfigurationPage : ContentPage
{
public event EventHandler SaveToDatabaseCompleted;
public ConfigurationPage()
{
BackgroundColor = Color.White;

        var viewModel = new ConfigurationViewModel(this);
        BindingContext = viewModel;

        var lblIPAddress = new Label
        {
            Text = "IP Address",
            TextColor = Color.Black
        };

        var IPAddress = new Entry
        {
            Text = string.Empty,
            TextColor = Color.White,
            BackgroundColor = Color.Blue,
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        IPAddress.SetBinding(Entry.TextProperty, "IPAddress");

        var lblUserName = new Label
        {
            Text = "UserName",
            TextColor = Color.Black
        };

        var UserName = new Entry
        {
            Text = string.Empty,
            TextColor = Color.White,
            BackgroundColor = Color.Blue,
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        UserName.SetBinding(Entry.TextProperty, "UserName");

        var lblPassword = new Label
        {
            Text = "Password",
            TextColor = Color.Black
        };

        var Password = new Entry
        {
            Text = string.Empty,
            TextColor = Color.White,
            BackgroundColor = Color.Blue,
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        Password.SetBinding(Entry.TextProperty, "Password");

        var lblXml = new Label
        {
            Text = "XML Page",
            TextColor = Color.Black,
        };

        Picker picker = new Picker
        {
            Title = "XML Settings",
            BackgroundColor = Color.Blue,
            VerticalOptions = LayoutOptions.FillAndExpand
        };

        var options = new List<string> { "val1.xml", "val2.xml" };

        foreach (string optionName in options)
        {
            picker.Items.Add(optionName);
        }

        string selected = string.Empty;

        var lblXMLEntry = new Label
        {
            Text = "Selected XML Value",
            TextColor = Color.Black
        };

        var XML = new Entry
        {
            IsEnabled = false,
            Text = selected,
            TextColor = Color.White,
            BackgroundColor = Color.Blue,
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        XML.SetBinding(Entry.TextProperty, "XML");

        picker.SelectedIndexChanged += (sender, args) =>
        {
            if (picker.SelectedIndex == 0)
                selected = picker.Items[0];
            else if (picker.SelectedIndex == 1)
                selected = picker.Items[1];

            XML.Text = selected;
        };

        var IPAddressLblStack = new StackLayout
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Orientation = StackOrientation.Horizontal,

            Children = {
                lblIPAddress
            }
        };

        var UserNameLblStack = new StackLayout
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Orientation = StackOrientation.Horizontal,

            Children = {
                lblUserName
            }
        };

        var PasswordLblStack = new StackLayout
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Orientation = StackOrientation.Horizontal,

            Children = {
                lblPassword
            }
        };

        var XMLLblStack = new StackLayout
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Orientation = StackOrientation.Horizontal,

            Children = {
                lblXml
            }
        };

        var PickerStack = new StackLayout
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Orientation = StackOrientation.Horizontal,

            Children = {
                picker
            }
        };

        var XMLLblEntry = new StackLayout
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Orientation = StackOrientation.Horizontal,

            Children = {
                lblXMLEntry
            }
        };

        var gateGridLayout = new Grid
        {
            Padding = new Thickness(5),
            VerticalOptions = LayoutOptions.CenterAndExpand,
            HorizontalOptions = LayoutOptions.CenterAndExpand,

            RowDefinitions = {
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) },
                new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) }
            },
            ColumnDefinitions = {
                new ColumnDefinition{ Width = GridLength.Auto }
            }
        };

        gateGridLayout.Children.Add(IPAddressLblStack, 0, 1);
        gateGridLayout.Children.Add(IPAddress, 0, 2);
        gateGridLayout.Children.Add(UserNameLblStack, 0, 3);
        gateGridLayout.Children.Add(UserName, 0, 4);
        gateGridLayout.Children.Add(PasswordLblStack, 0, 5);
        gateGridLayout.Children.Add(Password, 0, 6);
        gateGridLayout.Children.Add(XMLLblStack, 0, 7);
        gateGridLayout.Children.Add(PickerStack, 0, 8);
        gateGridLayout.Children.Add(XMLLblEntry, 0, 9);
        gateGridLayout.Children.Add(XML, 0, 10);

        var saveButtonToolbar = new ToolbarItem();
        saveButtonToolbar.Text = "Save";
        saveButtonToolbar.SetBinding(ToolbarItem.CommandProperty, "SaveButtonTapped");
        saveButtonToolbar.Priority = 0;
        ToolbarItems.Add(saveButtonToolbar);

        var cancelButtonToolbar = new ToolbarItem();
        cancelButtonToolbar.Text = "Cancel";
        cancelButtonToolbar.Command = new Command(async () => await PopModalAsync(true));
        cancelButtonToolbar.Priority = 1;
        ToolbarItems.Add(cancelButtonToolbar);

        Content = gateGridLayout;
    }

    public void HandleSaveToDatabaseCompleted(object sender, EventArgs e)
    {
        if (SaveToDatabaseCompleted != null)
            SaveToDatabaseCompleted(this, new EventArgs());
    }

    public async Task PopModalAsync(bool isAnimated)
    {
        await Navigation.PopModalAsync(true);
    }

}

`

VIEW MODEL
`
public class ConfigurationViewModel : BaseViewModel
{
LaneConfiguration laneModel;
Regex ip = new Regex(@\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b);

    public string IPAddress
    {
        get { return laneModel.IPAddress; }
        set
        {
            laneModel.IPAddress = value;
            OnPropertyChanged("IPAddress");
        }
    }

    public string UserName
    {
        get { return laneModel.UserName; }
        set
        {
            laneModel.UserName = value;
            OnPropertyChanged("UserName");
        }
    }

    public string Password
    {
        get { return laneModel.Password; }
        set
        {
            laneModel.Password = value;
            OnPropertyChanged("Password");
        }
    }

    public string XML
    {
        get { return laneModel.XML; }
        set
        {
            laneModel.XML = value;
            OnPropertyChanged("XML");
        }
    }

    public ICommand SaveButtonTapped { protected set; get; }

    public ConfigurationViewModel(ConfigurationPage page)
    {
        laneModel = new LaneConfiguration();

        SaveButtonTapped = new Command(() =>
        {
            bool IPPassed = false;

            if (laneModel.IPAddress == string.Empty)
            {
                //****************************************
                //HERE
                //****************************************
                //DisplayAlert("Configuration", "An IP Address is required.", "OK");
                return;
            }

            IPPassed = ValidateIP(laneModel.IPAddress);

            if (!IPPassed)
            {
                //****************************************
                //HERE
                //****************************************
                //DisplayAlert("Configuration", "An invalid IP was entered.", "OK");
                return;
            }

            Task.Run(() => new ConfigurationDatabase().AddLane(laneModel.IPAddress, laneModel.UserName, 
                                                                   laneModel.Password, laneModel.XML));
            page.HandleSaveToDatabaseCompleted(page, new EventArgs());
        });
    }

    private bool ValidateIP(string IP)
    {
        int n;
        bool isNumeric = false;
        bool Passed = true;
        string Port = string.Empty;
        String IPAddress = string.Empty;

        if (IP.Contains(":"))
        {
            if (IP.Length > IP.IndexOf(":") + 1)
                Port = IP.Substring(IP.IndexOf(":") + 1, IP.Length - (IP.IndexOf(":") + 1));

            isNumeric = int.TryParse(Port, out n);

            IPAddress = IP.Substring(0, IP.IndexOf(":"));
        }
        else
        {
            IPAddress = IP;
        }

        MatchCollection result = ip.Matches(IPAddress);

        if (result.Count == 0)
            return false;

        if (IP.Contains(":") && isNumeric == false)
            return false;

        return true;
    }
}

`

Best Answer

Answers

Sign In or Register to comment.