Tuesday, November 14, 2006

FormErrorCollection - Errors Property


Custom validation with managed code will be improved in InfoPath 2007. Several new classes provides the possibility to generate data validation errors in code.

In InfoPath 2003 it was possible to generate errormessages (in JScript or through the .NET framework), but it wasn't possible to draw a border around the field which indicates the error.

InfoPath 2007 provides a FormErrorCollection containing FormError objects in the XmlForm as the 'Errors' property.

Methods
1. Errors.Add(XPathNavigator context, string name, string message);
It act like a Key/Value (name/message) collection and each error points to the node to which the error is associated (context).

2.
Errors.Delete(string name);
You can remove the FormError by using the Key in the Errors.Delete method.


Example

public void InternalStartup()
{
// ...
EventManager.XmlEvents["/my:myFields/my:SampleField"].Validating +=
new XmlValidatingEventHandler(SampleField_Validating);
// ...
}

//Right-click on the control > Programming > Validating Event ...
public void SampleField_Validating(object sender, XmlValidatingEventArgs e)
{
// check if the new value isn't empty
if (!String.IsNullOrEmpty(e.NewValue))
{
//current fieldvalue cannot be 'example'
if (e.NewValue.ToLower().Equals("example"))
{
//e.Site points to the node that is being changed, e.Site is always the reference to the field which you are validating at that moment
Errors.Add(e.Site, "Error_SampleField", "Invalid fieldvalue");
}
else // all other values are allowed
{
Errors.Delete("Error_SampleField");
}
}
}



Conclusion
a The FormErrorCollection is also accessible in Form Services 2007 !
a It acts like the 'real' Data Validation (at design time)
a You cannot submit the form without resolving the errors !
Microsoft InfoPath 2007 Object Model
2007 Office System: Developer Posters

1 comment:

Alex Weinstein said...

Awesome article! Thanks, Kristof!