From b6043126fae039c58512f60a576b10925b06df4c Mon Sep 17 00:00:00 2001 From: crupest Date: Wed, 29 Jan 2020 00:17:45 +0800 Subject: ... --- Timeline/Models/Validation/Validator.cs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'Timeline/Models/Validation/Validator.cs') diff --git a/Timeline/Models/Validation/Validator.cs b/Timeline/Models/Validation/Validator.cs index a16f6f81..ead7dbef 100644 --- a/Timeline/Models/Validation/Validator.cs +++ b/Timeline/Models/Validation/Validator.cs @@ -20,24 +20,46 @@ namespace Timeline.Models.Validation (bool, string) Validate(object? value); } + public static class ValidatorExtensions + { + public static bool Validate(this IValidator validator, object? value, out string message) + { + if (validator == null) + throw new ArgumentNullException(nameof(validator)); + + var (r, m) = validator.Validate(value); + message = m; + return r; + } + } + /// /// Convenient base class for validator. /// /// The type of accepted value. /// /// Subclass should override to do the real validation. - /// This class will check the nullity and type of value. If value is null or not of type - /// it will return false and not call . + /// This class will check the nullity and type of value. + /// If value is null, it will pass or fail depending on . + /// If value is not null and not of type + /// it will fail and not call . + /// + /// is true by default. /// /// If you want some other behaviours, write the validator from scratch. /// public abstract class Validator : IValidator { + protected bool PermitNull { get; set; } = true; + public (bool, string) Validate(object? value) { if (value == null) { - return (false, ValidatorMessageNull); + if (PermitNull) + return (true, GetSuccessMessage()); + else + return (false, ValidatorMessageNull); } if (value is T v) -- cgit v1.2.3