3

How do you validate a class using Validation attributes when validating strongly typed view models.

Suppose you have a view model like so:

[PropertiesMustMatch("Admin.Password", "Admin.ConfirmPassword")]
public class AdminsEditViewModel
{
    public AdminsEditViewModel()
    {
        this.Admin = new Admin(); // this is an Admin class
    }

    public IEnumerable<SelectListItem> SelectAdminsInGroup { get; set; }


    public IEnumerable<SelectListItem> SelectAdminsNotInGroup { get; set; }

    public Admin Admin { get; set; }
}

I get null exception when on this line of PropertiesMustMatchAttribute

object originalValue = properties.Find(OriginalProperty,  true /* ignoreCase */).GetValue(value);

since Password field is a property of Admin class and NOT AdminsEditViewModel. How do I make it so that it will go so many levels deep until it does find property of Admin in the ViewModel AdminsEditViewModel? thanks

1 Answer 1

1

You need to modify the PropertiesMustMatchAttribute class to parse the property name and search deeply.

This attribute is not part of the framework; it's included in the default MVC template (in AccountModels.cs)
You can therefore modify it to suit your needs.

Specifically, you would call name.Split('.'), then loop through splitted names and get the property values.
It would look something like

object GetValue(object obj, string properties) {
    foreach(strong prop in properties)
        obj = TypeDescriptor.GetProperties(obj)
                            .Find(prop, ignoreCase: true)
                            .GetValue(obj);
    }
    return obj;
}
Sign up to request clarification or add additional context in comments.

2 Comments

not sure how to do it. can you please provide more info on this. thanks
@Shane: Here you go. (untested)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.