Search code examples
silverlightvalidationria

Force validation of ria entity in Silverlight 4


I have a situation in which I will load invalid data. I'm using a DataForm to edit the data and I need to force a validation. The user might not normally edit the fields which are invalid but before I save the entity back I would like to notify the user that they need to be edited. But the validation does not seem to fire unless the property is actually changed. Is there a way to force an entity to run all client side validation rules?

Shane Holder


Solution

  • I found this exact problem. I ended up implemented INotifyDataErrorInfo on my viewmodel (actually in a base class), and validating the validation context like so...

    // Clear any validation errors already registered
    CurrentUser.ValidationErrors.Clear();
    
    var validationResults = new List<ValidationResult>();
    ValidationContext vcontext = new ValidationContext(CurrentUser, null, null);
    
    // Validate the User; the results are added to our list of validationResults
    Validator.TryValidateObject(CurrentUser, vcontext, validationResults);
    
    // Add the errors to the entities validation error list
    foreach (var res in validationResults)
    {
        CurrentUser.ValidationErrors.Add(res);
    }
    

    I can't remember off the top of my head, but if that doesn't trigger the ValidationStates on your view (i.e. a red border on the textbox), add the errors to the viewmodel's ValidationErrors collection (created in the implementation of INotifyDataErrorInfo).

    // Add the errors to the viewmodel's validation error list
    foreach (var res in validationResults)
    {
        CurrentUser.ValidationErrors.Add(res);
    }