diff options
author | 杨宇千 <crupest@outlook.com> | 2020-02-01 00:26:35 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-02-01 00:26:35 +0800 |
commit | d703269e06d4c9e254fe2d5589ff04cdd6a9b366 (patch) | |
tree | f02f8d57440c777d4732bc4439f82e8b25c6732c /Timeline/Models/Validation/Validator.cs | |
parent | 631731e5c2253116a53fdc435afca184251a34fc (diff) | |
parent | bddf1d6eaac782672071df6527c40c81c3123f3a (diff) | |
download | timeline-d703269e06d4c9e254fe2d5589ff04cdd6a9b366.tar.gz timeline-d703269e06d4c9e254fe2d5589ff04cdd6a9b366.tar.bz2 timeline-d703269e06d4c9e254fe2d5589ff04cdd6a9b366.zip |
Merge pull request #56 from crupest/dev
Refactor API to be RESTful.
Diffstat (limited to 'Timeline/Models/Validation/Validator.cs')
-rw-r--r-- | Timeline/Models/Validation/Validator.cs | 28 |
1 files changed, 25 insertions, 3 deletions
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;
+ }
+ }
+
/// <summary>
/// Convenient base class for validator.
/// </summary>
/// <typeparam name="T">The type of accepted value.</typeparam>
/// <remarks>
/// Subclass should override <see cref="DoValidate(T, out string)"/> to do the real validation.
- /// This class will check the nullity and type of value. If value is null or not of type <typeparamref name="T"/>
- /// it will return false and not call <see cref="DoValidate(T, out string)"/>.
+ /// This class will check the nullity and type of value.
+ /// If value is null, it will pass or fail depending on <see cref="PermitNull"/>.
+ /// If value is not null and not of type <typeparamref name="T"/>
+ /// it will fail and not call <see cref="DoValidate(T, out string)"/>.
+ ///
+ /// <see cref="PermitNull"/> is true by default.
///
/// If you want some other behaviours, write the validator from scratch.
/// </remarks>
public abstract class Validator<T> : 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)
|