Saturday, March 24, 2012

Validation in FormView how do you do it?

I have a FormView control with several fields in Edit mode, and I have validation controls for each one. This is what I am currently doing to attempt to prevent updating when an invalid entry is made:

void formViewInventory_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
// check if entries are valid
RequiredFieldValidator reqval1 = (RequiredFieldValidator)formViewInventory.Row.FindControl("reqvalExpDate");
CompareValidator compval1 = (CompareValidator)formViewInventory.Row.FindControl("compvalExpDate");
RegularExpressionValidator regexp1 = (RegularExpressionValidator)formViewInventory.FindControl("regexpBldg");
RegularExpressionValidator regexp2 = (RegularExpressionValidator)formViewInventory.FindControl("regexpCabinet");
RegularExpressionValidator regexp3 = (RegularExpressionValidator)formViewInventory.FindControl("regexpQty");
RegularExpressionValidator regexp4 = (RegularExpressionValidator)formViewInventory.FindControl("regexpUnits");
RegularExpressionValidator regexp5 = (RegularExpressionValidator)formViewInventory.FindControl("regexpQtyUsed");
RegularExpressionValidator regexp6 = (RegularExpressionValidator)formViewInventory.FindControl("regexpNotes");
bool valid1 = reqval1.IsValid;
bool valid2 = compval1.IsValid;
bool valid3 = regexp1.IsValid;
bool valid4 = regexp2.IsValid;
bool valid5 = regexp3.IsValid;
bool valid6 = regexp4.IsValid;
bool valid7 = regexp5.IsValid;
bool valid8 = regexp6.IsValid;
if (!valid1 || !valid2 || !valid3 || !valid4 || !valid5 || !valid6 || !valid7 || !valid8)
{
e.Cancel = true;
}
}

However, it's not working -- the database is updated even when an invalid entry is made, and the error message shows up briefly on the screen. By the time it gets to this event handler, all the validators resolve to TRUE.

What am I doing wrong?

Hi Cynthia,

The FormView class has a method InsertItem( ) with an overloaded version that takes CausesValidation parameter. I think that was meant to validate the form before trying to submit the changes to the provider, but apparently there is a bug and the validation is never called.

I resolved this problem by:

1) Made the Insert link button that comes with the insert template invisible
2) Created my own link button and set the text = "Insert"
3) Handled the click event of my link button and added:

Page.Validate();
FormViewEmployer.InsertItem(true);

That worked for me, now the entire validation is made upon the Page.Validate( ) call and the InsertItem will not run if there is any validation problem.

Hope that helps

Marcio Esteves
Portland-OR

No comments:

Post a Comment