Time Need to validate for timepicker in xamarin forms

Viewed 325

I need to validate a selected time from the time picker. So if the selected time is not valid then I need to display a toast message.

Which event will trigger if time will select from the time picker?

And I don't want to bind the time if the selected time is not valid based on my condition.

XAML Code:

<controls:DatePickerCustom FontSize="14" HeightRequest="35" Date="{Binding CustomDate,Mode=TwoWay}" MaximumDate="{Binding MaximumDate}" FontFamily="Segoe UI" Format="D" IsEnabled="{Binding IsDatePickerEnable}">
                                    <DatePicker.Triggers>
                                        <DataTrigger TargetType="DatePicker" Binding="{Binding IsCustomSelected}" Value="true">
                                            <Setter Property="TextColor" Value="{DynamicResource HeadingTextColor}" />
                                            <Setter Property="TextColor" Value="{DynamicResource HeadingTextColor}" />
                                        </DataTrigger>
                                    </DatePicker.Triggers>
                                </controls:DatePickerCustom>
2 Answers

Handle this in your "setter" for property CustomDate.

In a setter, the new value is value. If value isn't valid, Show the toast message. Return from setter, without changing the internal field that holds the value, and without calling OnPropertyChanged.

If you need more information, please show the code that declares property CustomDate.

It that property is currently an "auto-property", convert it to a "full-property" - this will have a "backing field", and gives you a place to do the test, and reject the change.

You could listen the PropertyChanged event of TimePicker,then match the Time property.

For example:

<TimePicker PropertyChanged="TimePicker_PropertyChanged"></TimePicker>


private void TimePicker_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        TimePicker timePicker = sender as TimePicker;
        if (e.PropertyName.Equals("Time") )
        {
            var time = timePicker.Time;
            if (time.Minutes == 10) // your condition
            {

            }
            else
            {
                DisplayAlert("Warning", "This is a validate time", "Cancel");
            }
        }
    }
Related