views:

955

answers:

1

How to apply validations to WPF datepicker toolkit? I want it to error out if invalid date is selected and in some case I have Arrival and Departure dates, so I want to validate it to see that the arrival date is not later than the departure date.

+1  A: 

It seems a year above date picker validation was a problem. Anyway, now it works.

I am not a WPF specialist, bu I'll try to give you an idea

write a validation rule

public class DateExpiredRule : ValidationRule
{

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        DateTime orderDate = (DateTime)value;

        return new ValidationResult(orderDate < DateTime.Now, "Please, enter date before Now()");
    }
}

then you can attach it to datepicker

    <!-- since validation works hand by hand with binding, 
        I use hidden datepicker as binding source -->
    <WPFToolkit:DatePicker Name="dateProvider" Visibility="Collapsed">
    </WPFToolkit:DatePicker>

    <WPFToolkit:DatePicker Name="notExpired">
        <WPFToolkit:DatePicker.SelectedDate>
            <Binding ElementName="dateProvider" Path="SelectedDate" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <local:DateExpiredRule/>
                </Binding.ValidationRules>
            </Binding>
        </WPFToolkit:DatePicker.SelectedDate>
    </WPFToolkit:DatePicker>

specify control template when validation error occurs. By default validation error changes border color. I used additional tooltip when mouse is over control.

alt text

source code

About 'picker to picker' validation.

I know that one can use custom properties in validation rules (see AgeRangeRule in msdn example)

Maybe you should use this feature like this

<local:MaxDateRule MaxDate="{Binding ElementName=DepartureDatePicker, Path=SelectedDate" />

but in order to apply binding you need to make MaxDate a DependencyProperty .. you should definetly ask a guru ;)

Instead of highlighting you should consider intercepting the datepicker value change (via some kind of datepicker 'onchange' event) and accept or reject the change.

jonny
Thanks so much for your reply..I had a question, how shall I validate dates in 2 datepickers. Eg, I have arrival date datepicker and departure date datepicker. How shall I validate this two so that the arrival date is always less than (before), the departure date?
developer