How can I add minimum date validation check for DatePicker in Xamarin

Viewed 3309

I am having two DatePicker (named fromdate and todate) and a button (named as save).

By default, today's date will be populated in both the DatePicker. And I have added minimum date validation ( the user can select only today's or greater date.

If today's date is 30th May and the user selects 15th June from fromdate and clicked ok. Now the default today date is displayed in todate. I want a validation like if the user selects 15th June in fromdate and click ok, then the todate should be populated with fromdate.

2 Answers

So you have two DatePickers: fromDate and toDate.

You can add an attribute to your fromDate which is called "PropertyChanged":

<DatePicker
x:Name="fromDate"
PropertyChanged="FromDate_Changed"
/>

<DatePicker
x:Name="toDate"
/>

Now you can go in your xaml.cs file and add the following to the constructor:

public ItemsPage()
{
    InitializeComponent();
    fromDate.MinimumDate = DateTime.Now;
    toDate.MinimumDate = DateTime.Now;
}

Now with both DatePickers you have to pick a date which is not from the past.

Then you can create the method "FromDate_Changed" (if it has not been created automatically):

private void FromDate_Changed(object sender, PropertyChangedEventArgs e)
{
    toDate.MinimumDate = fromDate.Date;
}

Now everytime when you change the date from the fromDate picker, the minimum date from toDate will automatically change to the date you selected in fromDate.

I know this question is 2 years old, but maybe for the future if someone is looking for exactly that problem, he will find an easier solution.

Excuse my english please.

Related