field validation with reflection

D

Dan

hi newsgroup,

i need server side validation of user entries.
as i do have many fields, i would like to use reflection for checkinng
the IsValid property of all the Validators.
here is the reflection code

i don't understand why i get the following error:
Object does not match target type.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.Reflection.TargetException: Object does not
match target type.

at this line: object
ret=field.FieldType.GetProperty("IsValid",typeof(bool)).GetValue(field,null);

the code is a loop the goes through all public fields of the user control:
public static bool checkValidators(Control page)
{
bool isValid=true;
FieldInfo[] fields=page.GetType().GetFields();
foreach(FieldInfo field in fields)
{

if(field.FieldType.IsSubclassOf(typeof(System.Web.UI.WebControls.BaseValidator)))
{

object
ret=field.FieldType.GetProperty("IsValid",typeof(bool)).GetValue(field,null);
isValid=Convert.ToBoolean(ret);
}
}
return isValid;
}

any ideas?
or maye there is another way to check the IsValid property of all the
validators in a fast way?
thanks for your help.
dan
 
A

Anders Norås

or maye there is another way to check the IsValid property of all the
validators in a fast way?
I could have sorted your reflection problem, but I think Page.IsValid is
what you should use. This method returns true if all validators on a page
return true, otherwise it returns false.

Anders Norås
blog: http://dotnetjunkies.com/weblog/anoras/
 
J

John M Deal

If you want to find out more information that just Page.IsValid (such as
which validators failed or the messages that they contain) this should
get you on the right track (watch for word wrap):

foreach (Control currentControl in this.Page.Validators)
{
IValidator currentValidator = currentControl as IValidator;
if (currentValidator != null)
{
if (!currentValidator.IsValid)
{
Label currentValidationMessage = new Label();
currentValidationMessage.Text = currentValidator.ErrorMessage;
//Do something with the label (or whatever)
}
}
}

I used a variant of this to create my own display of the messages that
were to be displayed when validators failed. Hope it helps.

Have A Better One!

John M Deal, MCP
Necessity Software
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,591
Members
45,100
Latest member
MelodeeFaj
Top