开发者

Custom Validation is only run once

I am creating an MVVM Silverlight application and am trying to add validation to my Model.

开发者_Go百科

In this particular instance I have multiple phone number boxes and have the requirement that at least one phone number must be entered. To facilitate I have my properties (HomePhone, WorkPhone, MobilePhone and OtherPhone) on my model decorated with an a CustomValidation attribute.

Example property:

    private string _otherPhone;
    [CustomValidation(typeof(MyModel), "ValidatePhoneNumbers")]
    public string OtherPhone
    {
        get { return _otherPhone; }
        set
        {
            if (_otherPhone == value) return;
            _otherPhone = value;
            Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "OtherPhone" });
            RaisePropertyChanged(() => HomePhone);
            RaisePropertyChanged(() => WorkPhone);
            RaisePropertyChanged(() => MobilePhone);
            RaisePropertyChanged(() => OtherPhone);
        }
    }

Along with the custom validator itself:

    public static ValidationResult ValidatePhoneNumbers(string number, ValidationContext validationContext)
    {
        MyModel myModel = (MyModel)validationContext.ObjectInstance;
        return string.IsNullOrEmpty(myModel.HomePhone) && string.IsNullOrEmpty(myModel.WorkPhone) && string.IsNullOrEmpty(myModel.MobilePhone) && string.IsNullOrEmpty(myModel.OtherPhone)
                   ? new ValidationResult("At least one phone number must be entered")
                   : ValidationResult.Success;
    }

I have ensured that the backing store is set in the property setter before the validation is run, to ensure that the ValidatePhoneNumbers method is able to check the latest value.

When I try to save my model, I am executing UpdateBindingExpression on all the bindings in the View. Now this works correctly the first time that I try to save, and all four fields are highlighted as having an error.

If I try to save again however, all fields are marked as passed validation, and a breakpoint in ValidatePhoneNumbers is never hit. Why is this?

Thanks


I'm sure that every time that I spend long enough fighting a bug to resort to posting on SO, I work out what the actual answer is 20 seconds later... The if (_otherPhone == value) return; was causing the validation not to run - this optimisation would make sense if the validation wasn't dependent on another property.

Never mind...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜