-
Notifications
You must be signed in to change notification settings - Fork 3
Extending TNValidate
If you want to add another language, currently you need to modify the library itself (in the future, we may add a way of adding a new language without doing that). Thankfully, however, it's a simple process.
First, go into the the Validation\Languages directory of the project. There are XML files in there with names such as Languages.en.xml (this is the English one). Copy this file (or another one that you want to use as your translation base). Go through the file and translate all of the strings in it.
Once you have done this, you just need to register your new language in the ValidationLanguageEnum. It has entries like this:
[LanguageResourceFile("TNValidate.Languages.Languages.en.xml")]
English = 0,
[LanguageResourceFile("TNValidate.Languages.Languages.sv.xml")]
Swedish = 1
So to add, for example, Slovak, you would just add an entry to the enum:
[LanguageResourceFile("TNValidate.Languages.Languages.sk.xml")]
Slovak = 2
And you're done. Note that we use ITEF naming scheme; that means you can use the ISO 639-1 codes, unless you need to distinguish a region (e.g. we have pt-br for Brazilian Portuguese).
You can use extension methods to add extra rules to validate types that we already validate. For example, here we take the IntValidator and add a validation rule IsTheAnswer which checks if the value is 42.
static class CustomIntRules
{
public static IntValidator IsTheAnswer(this IntValidator IV)
{
// First parameter is True if the condition does **not** match.
// Second parameter is the error message we will give.
IV.SetResult(IV.Value != 42, IV.FieldName + " must be The Answer.");
// Return the invocant to allow chaining.
return IV;
}
}
After you do this, you can then use the rule like any other.
Validate.That(Result, "Result").IsTheAnswer();
If you want to validate a type other than those supported by TNValidate, you need to define a validator of your own. This is a two step process.
-
Subclass ValidatorBase (this is a generic base class; you need to pass as type parameters the type that your validator will validate and also the class of the validator you are defining)
-
Define an extension method called That on the class Validator. This will serve as another overload and will need to instantiate and return an instance of your Validator. We'll try and post an example of this here shortly.