From 3ddb38839ac07de4edf071faeb753b62acb0bed1 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Tue, 22 Oct 2019 20:49:52 +0800 Subject: ... --- Timeline/Models/Validation/UsernameValidator.cs | 37 ++++++++++--------------- 1 file changed, 15 insertions(+), 22 deletions(-) (limited to 'Timeline/Models/Validation/UsernameValidator.cs') diff --git a/Timeline/Models/Validation/UsernameValidator.cs b/Timeline/Models/Validation/UsernameValidator.cs index ecc3b5b3..65d4da71 100644 --- a/Timeline/Models/Validation/UsernameValidator.cs +++ b/Timeline/Models/Validation/UsernameValidator.cs @@ -1,46 +1,39 @@ -using Microsoft.Extensions.Localization; -using System.Linq; -using System.Text.RegularExpressions; +using System.Linq; namespace Timeline.Models.Validation { public class UsernameValidator : Validator { public const int MaxLength = 26; - public const string RegexPattern = @"^[a-zA-Z0-9_][a-zA-Z0-9-_]*$"; - private readonly Regex _regex = new Regex(RegexPattern); - - protected override bool DoValidate(string value, IStringLocalizerFactory localizerFactory, out string message) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "Already checked in base class.")] + protected override (bool, ValidationMessageGenerator) DoValidate(string value) { if (value.Length == 0) { - message = "An empty string is not permitted."; - return false; + return (false, factory => + factory?.Create(typeof(UsernameValidator))?["ValidationMessageEmptyString"] + ?? Resources.Models.Validation.UsernameValidator.InvariantValidationMessageEmptyString); } if (value.Length > 26) { - message = $"Too long, more than 26 characters is not premitted, found {value.Length}."; - return false; + return (false, factory => + factory?.Create(typeof(UsernameValidator))?["ValidationMessageTooLong"] + ?? Resources.Models.Validation.UsernameValidator.InvariantValidationMessageTooLong); } foreach ((char c, int i) in value.Select((c, i) => (c, i))) - if (char.IsWhiteSpace(c)) + { + if (!(char.IsLetterOrDigit(c) || c == '-' || c == '_')) { - message = $"A whitespace is found at {i} . Whitespace is not permited."; - return false; + return (false, factory => + factory?.Create(typeof(UsernameValidator))?["ValidationMessageInvalidChar"] + ?? Resources.Models.Validation.UsernameValidator.InvariantValidationMessageInvalidChar); } - - var match = _regex.Match(value); - if (!match.Success) - { - message = "Regex match failed."; - return false; } - message = ValidationConstants.SuccessMessage; - return true; + return (true, SuccessMessageGenerator); } } } -- cgit v1.2.3