简体   繁体   中英

Form Validation in Xamarin

In my Xamarin App, the form is Dynamic, means the Form is been Fetch from API. Then I Get the Entry Value from Dynamic Form in ViewModel and send it in Array within multipart/form-data to the server.

ViewModel

public class Form
{
    public string name { get; set; }
    public string label { get; set; }
    public string Value { get; set; }
}

private ObservableCollection<Form> _form = new ObservableCollection<Form>();
public ObservableCollection<Form> Form
{
    get => _form;
    set => this.RaiseAndSetIfChanged(ref _form, value);

}

public ObservableCollection<Form> Value
{
    get => _form;
    set => this.RaiseAndSetIfChanged(ref _form, value);
}

.XAML

<StackLayout BindableLayout.ItemsSource="{Binding Form}">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <Entry x:Name="{Binding name}"
                   Text="{Binding Value}"
                   Placeholder="{Binding label}">
            </Entry>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>

Now, I just want to check, if Form.Value (for all the fields) aren't null. Basically, I've a button in .xaml page, which is disable by default, so if all the fields are filled, Enabled that button (using bindable properties).

I wrote this piece of code, but the problem is that, if the last entry is filled and others are null, it will enable the button.

foreach (var item in Value.ToList())
{
    if (!(string.IsNullOrEmpty(item.Value)))
    {
        IsEnabledSubmitButton = true;
    }
}

Your logic is backwards. For Validation, you generally want to start with the assumption that the form is valid, and then check if any individual field is NOT valid, invalidate the Form.

IsEnabledSubmitButton = true;

foreach (var item in Value.ToList())
{
    if (string.IsNullOrEmpty(item.Value))
    {
        IsEnabledSubmitButton = false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM