Converters handle validation during content entry and persistence
- (page 5 of 7)
Validation code to is added to the GetObject call. The code below replaces the GetObject method in Converter.
/// <summary>
/// Gets the integer which represents the string
/// </summary>
/// <param name="str">string which represents an integer</param>
/// <param name="context">Context in which we are editing</param>
/// <returns>Integer</returns>
public object GetObject(string str, System.Collections.IDictionary context)
{
try
{
if (str == null || str.Length == 0)
{
if (this.def.IsRequired)
{
throw new ConverterValidationException("Field "+def.FieldName+" is not specified but is marked as required");
}
else
return null;
}
Int32 val = Int32.Parse(str);
// Validation code
if (val < 0 || val > 600)
{
throw new ConverterValidationException("Field "+def.FieldName+" has a value outside of the range 0-600, value is "+str);
}
if (val % 3 != 0)
throw new ConverterValidationException("Field "+def.FieldName+" has a value not divisible by 3, value is "+str);
// End of validation code
return val;
}
catch (Exception e)
{
throw new ConverterValidationException("Can't convert value "+str+" using converter IntegerDivisibleConverter", e);
}
}
Now when we test the application and see that the field now does not accept integers which are not divisible by 3 or that are more than 600.
We also need to add in the method to handle altering the XmlSchema, this is used in the content definition dialog box, when we are viewing the schema.
Add the code below, and also add in the using statements System.Xml and System.Xml.Schema.
/// <summary>
/// Allows for the XmlSchema that represents the entire content to be modified to represent specific validation.
/// </summary>
/// <param name="user">Logged on user</param>
/// <param name="type">Simple type to modify</param>
public void ModifyXmlSchemaType(Ant.Security.AuthenticatedUser user, System.Xml.Schema.XmlSchemaSimpleType type)
{
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.BaseTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema");
{
XmlSchemaMinInclusiveFacet facet = new XmlSchemaMinInclusiveFacet();
facet.Value = "0";
restriction.Facets.Add(facet);
}
{
XmlSchemaMaxInclusiveFacet facet = new XmlSchemaMaxInclusiveFacet();
facet.Value = "600";
restriction.Facets.Add(facet);
}
}