field validation with reflection

  • Thread starter Thread starter Dan
  • Start date Start date
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
 
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
 
Back
Top