Property validation
Checking optional properties
Because a property can be optional, your template may need to check whether the user entered a value. For example, you might let the user decide whether the generated class is wrapped in a namespace. First, declare an optional property:
<%@ Property Name="ClassNamespace" Type="System.String" Optional="True" Category="Context" Description="The namespace that the generated class will be a member of." %>
Then check the value at generation time and write the namespace declaration only when there is one. In a C# template:
<% if (ClassNamespace != null && ClassNamespace.Length > 0)
{ %>namespace <%= ClassNamespace %>{<% }
%>
In a Visual Basic template:
<% If Not ClassNamespace Is Nothing AndAlso ClassNamespace.Length > 0 Then %>
Namespace <%= ClassNamespace %>
<% End If %>
Custom validation errors
Conditionals like the ones above change what gets generated. To stop generation altogether when a value is invalid, override the GetCustomValidationErrors method and return your own ValidationError objects.
This example validates an Age property. The default of 130 is deliberately out of range, so you can see the error:
<%@ Property Name="Age" Default="130" Type="System.Byte" %>
Import System.Collections.Generic so that you can use IEnumerable<T> and List<T>:
<%@ Import Namespace="System.Collections.Generic" %>
Then implement GetCustomValidationErrors in a script block. It returns an IEnumerable<ValidationError>; here it adds an error, with a message explaining the problem, when Age is greater than 125:
<script runat="template">
/// <summary>
/// Allows the developer to add custom ValidationErrors to the validation collection.
/// </summary>
public override IEnumerable<ValidationError> GetCustomValidationErrors() {
var errors = new List<ValidationError>();
if (Age > 125)
errors.Add(new ValidationError("Invalid Age, the oldest living person in history lived to 122 years old.", "Age"));
return errors;
}
</script>
When you try to generate with the default value, the template doesn't run, and your message appears in the Error window.