1

I'm writing my personalized validation and I would like to know if would be possible to retrieve more details about the object to validate.

    protected override ValidationResult IsValid(object value, 
                                          ValidationContext validationContext)
    {
        var currentObj = validationContext.ObjectInstance;
        // How can I find if this currentObj is Required???
        // Logic....

        return ValidationResult.Success;
    }

4 Answers 4

1

What you want to do is to find out if the property you have marked with your own validation attribute is also marked as [Required] ? If this is the case you can use reflection to check if the property already has a specific attribute (in this case required).

var property = validationContext.ObjectInstance.GetType().GetProperty(validationContext.MemberName);
if (property.IsDefined(typeof(RequiredAttribute), false)) 
{
   ... this means it does have the attribute
}

! I havent tested this code and have done this only a few times. Im not 100% sure the 'validationContext.MamberName' is truly the name of the property you have assigned your attribute to (though it should be). Nevertheless I have used this type of reflection to check if a property has an attribute assigned to it. May have to tweak it a little but I expect it to work ...

Sign up to request clarification or add additional context in comments.

4 Comments

validationContext.MemberName is equal to 'null' and even if I write .. .GetProperty("Required") the result is always 'null'. Do you have any ideas?
You are trying to get the property you assigned the attribute to, for instance if you have a class with a property int age, you want to take the property age, therefore - .GetProperty("age"). However this will bind your attribute to a specifically named property which will defeat the purpose of creating an attribute, will make it work only with specifically named properties which is ... not useful at all. You want to find a way to get the property you are validating (as PropertyInfo)
You can also try with validationContext.DisplayName. According to the documentation at : msdn.microsoft.com/en-us/library/… it should contain the name of the member you are trying to validate / even though the same is said about MemberName... Sry I dont have a way to test it right now
Thks Astian, you have been helpful.
0

That's a business rule. We can't know that. You can find properties and find their attributes, and for example perform a null check when the property in question carries a RequiredAttribute.

Comments

0

You can maintain required fields as a list.

            List<Control> requiredFieldlst;
            private void setupControlsToValidate()
            {
                requiredFieldlst = new List<Control>();
                requiredFieldlst.Add(txtCompanyName);
                requiredFieldlst.Add(txtBillingAddress);
                requiredFieldlst.Add(txtCity);

            }

Then You may call this method in your page load. And when at your button click or any other event you can use below method to check if all the required fields have filled

            private bool InputValidation()
            {

                foreach (Control thisControl in requiredFieldlst) //Required fields and special character validation
                {
                    if (string.IsNullOrEmpty(((TextBox)thisControl).Text))
                    {
                        //Do not save, show messagebox.
                        MessageBox.Show("Some required Fields are missing....!", "Error", MessageBoxButtons.OK);
                        ((TextBox)thisControl).Focus();
                        return false;
                    }

                }

Comments

0

Astian thanks for your suggestion: it was "almost" correct :) Here the code that I used in order to achieve my task (I do not know if it is the best one):

string nameOfMyObject = "objRequired";    
var property = validationContext.ObjectInstance.GetType().GetProperty(nameOfMyObject);
bool flagIsRequired = property.IsDefined(typeof(RequiredAttribute), true);
if(flagIsRequired){
    ......

Hope this can help!

Comments

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.