-
Notifications
You must be signed in to change notification settings - Fork 9
Format Support
This library supports following formats currently:
- uri
- uri-reference
- date
- time
- date-time
- uuid
- hostname
- ipv4
- ipv6
- json-pointer
- regex
If you need to support an additional format, implement a custom FormatValidator and register it before creating the JsonValidator that uses it:
public class TestCustomFormatValidator : FormatValidator
{
public override bool Validate(string content)
{
// custom format validation logic here...
}
}
// register it globally
FormatRegistry.Global.AddFormat("custom_format", () => new TestCustomFormatValidator());The factory passed to AddFormat is evaluated lazily. The created validator is cached and reused by the registry, so custom format validators should be stateless and thread-safe.
Besides registering custom formats in the process-wide FormatRegistry.Global, you can also register them on a specific JsonValidatorOptions instance through its FormatRegistry.
Custom formats registered this way are isolated to the JsonValidator instances created with that options instance, so different validators can use independent custom format rules:
var options = new JsonValidatorOptions();
options.FormatRegistry.AddFormat("custom_format", () => new TestCustomFormatValidator());
var validator = new JsonValidator(schema, options);A format validator is resolved per format name. The per-JsonValidatorOptions level FormatRegistry takes higher precedence than FormatRegistry.Global: the global registry is only consulted when the per-options registry has no implementation registered for that specific format name.
Sometimes you may want to override existing standard format validation logic, not only add a new format. You can do this globally with FormatRegistry.Global.SetFormat:
public class UpdatedDateTimeFormatValidator : FormatValidator
{
public override bool Validate(string content)
{
// custom format validation logic here...
}
}
// override it globally
FormatRegistry.Global.SetFormat("date-time", () => new UpdatedDateTimeFormatValidator());You can also override a standard format only for one JsonValidatorOptions instance:
var options = new JsonValidatorOptions();
options.FormatRegistry.SetFormat("date-time", () => new UpdatedDateTimeFormatValidator());
var validator = new JsonValidator(schema, options);In this case, only validators created with this options instance use UpdatedDateTimeFormatValidator for date-time; other validators continue using the global format registry.