Creating custom validators


It is very easy to both add your own validation attributes, or to create general project-wide validation rules that apply regardless of attributes, by creating your own custom validators. Here are a few examples.

The following validator will check all saved strings in the entire project, and generate a warning if the string is null or empty.

using Sirenix.OdinInspector.Editor.Validation;

[assembly: RegisterValidator(typeof(EmptyStringValidator))]

public class EmptyStringValidator : ValueValidator<string>
{
    protected override void Validate(string value, ValidationResult result)
    {
        if (string.IsNullOrEmpty(value))
        {
            result.ResultType = ValidationResultType.Warning;
            result.Message = "This string is empty! Are you sure that's correct?";
        }
    }
}

This validator will check any string value with [Regex] applied, and register an error if the string is not a valid regex pattern.

using System;
using System.Reflection;
using System.Text.RegularExpressions;
using Sirenix.OdinInspector.Editor.Validation;

[assembly: RegisterValidator(typeof(RegexValidator))]

public class RegexAttribute : Attribute { }

public class RegexValidator : AttributeValidator<RegexAttribute, string>
{
    protected override void Validate(object parentInstance, string memberValue, MemberInfo member, ValidationResult result)
    {
        try
        {
            Regex.Match("", memberValue);
        }
        catch (ArgumentException ex)
        {
            result.ResultType = ValidationResultType.Error;
            result.Message = "Invalid regex string: " + ex.Message;
        }
    }
}