Using TNValidate

The TNValidate Model

There are three steps to doing a validation with TNValidate.
  • Create a new instance of the Validator class. This instance will be used to validate a set of data and hold the results. (This means that you should create an instance each time you are doing some validation; since they are not intended to be shared and re-used, instances of Validator are not thread-safe.)
  • Validate one or more items of data by writing a chain of validation rules. Each validation rule you call hands back the validator object so that you can chain another rule onto the end.
  • Check if there were any validation errors, and present them to the end user if so, so they can correct them. An IList of the validation failures is handed back, which you may data-bind, for example to a Repeater control in ASP.NET, to present the failures.

Instantiating The Validator

The parameterless constructor of Validator defaults to English language for error message generation and only collects one error per field, even if there are several.

var Validate = new Validator();

Alternatively, you can specify the language that you wish to have automatically generated error messages in.

var Validate = new Validator(ValidationLanguageEnum.Swedish);

Or set that you want multiple errors collected per field:

var Validate = new Validator(ValidationLanguageEnum.Swedish, ErrorMode.AllErrors);

Describing A Validation

To start validating a field, call the That method on the Validate object, passing in the item of data that you want to validate and a human-readable name. This will be used in the auto-generated error messages. Depending on the type of the data item that you pass in, you will get back an object with methods for the different types of validation you can do. Currently you can pass in any of: int, string, DateTime.

After this, you simply chain on one or more method calls to do the required validation.

Validate.That(Email, "Email address").IsEmail();

If you are doing many bits of validation, you can spread it over many lines to improve readability:

Validate.That(Name, "Name")
        .IsLongerThan(3)
        .IsShorterThan(100);

You can validate as many fields as you wish before checking for success or failure of the validation.

Getting Failure Information

You can check if the validation was successful by calling the HasErrors method.

if (Validate.HasErrors())
{
    // Report errors.
}
else
{
    // Save/insert data, or whatever you do if it's OK...
}

You can also call the ErrorCount method to see how many failures there were.

Console.WriteLine("Oh noes, there were {0} errors!", Validate.ErrorCount());

To get a list of validation failures, use the ValidatorResults property. It returns something that does the IList interface, meaning you can iterate over it:

foreach (var Error in Validate.ValidatorResults)
    Console.WriteLine(Error.ValidationMessage);

Or data-bind it, for example to a Repeater control:

<asp:Repeater ID="ErrorList" runat="server">
    <HeaderTemplate><ul class="Errors"><HeaderTemplate>
    <ItemTemplate><li><%# DataBinder.Eval(Container.DataItem, "ValidationMessage") %></li></ItemTemplate>
    <FooterTemplate></ul><FooterTemplate>
</asp:Repeater>

With (in the code-behind):

ErrorList.DataSource = Validate.ValidatorResults;
ErrorList.DataBind();

Custom Error Messages

If you wish to supply a custom error message rather than getting the auto-generated one, just pass it in as another parameter to the validation method. That is, if for the default message you would write:

Validate.That(Age, "Age").IsGreaterThanOrEqual(13);

You would instead write:

Validate.That(Age, "Age").IsGreaterThanOrEqual(13, "You must be 13 or older to sign up");

You can have the field name and any arguments to the test substituted into your custom error using the {0}, {1}, {2} style syntax. For example:

Validate.That(Age, "Age").IsGreaterThanOrEqual(AgeLimit, "Your {0} must be at least {1} to sign up");

Would, supposing the AgeLimit variable contained 18, result in the error message "Your Age must be at least 18 to sign up". {0} always represents the name of the field being tested and {1} and {2} are the parameters passed to the rule, if any (some have none, some one, some two).

Negation

You may have noticed that so far all of the rules were testing that things were true. However, you can use .Not() before anything to invert it.

Validate.That(ID, "ID").Not().IsBetween(1000, 2000, "IDs cannot be in reserved range");

In general, you will be using positive conditions more than negative ones. In fact, they're shorter to write to encourage them to be used more; validating input by saying what you don't want is, quite often, the wrong thing to be doing and leads to validation that is too permissive.

Errors and Warnings

Sometimes you may want to flag up things that are worth warning about, but not have them count as an error. You can do this by calling the WarnUnless() method prior to the rule you want to have as the warning.

Validate.That(Age, "Age").IsGreaterThanOrEqual(13)
                         .WarnUnless().IsGreaterThanOrEqual(18);

If Age is, for example, 15 here, then the HasErrors() method will return false, since the second check is only a warning. However, HasWarnings() will return true, and getting the array of ValidatorResults will still provide the entry for the warning.

Last edited Jan 12, 2010 at 8:18 PM by jnthn, version 4

Comments

No comments yet.