From fc2196d0b6bed25b515997ad9d785f4471857a86 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Sat, 17 Aug 2019 19:25:08 +0800 Subject: Add validation. --- Timeline/Models/Validation/UsernameValidator.cs | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Timeline/Models/Validation/UsernameValidator.cs (limited to 'Timeline/Models/Validation/UsernameValidator.cs') diff --git a/Timeline/Models/Validation/UsernameValidator.cs b/Timeline/Models/Validation/UsernameValidator.cs new file mode 100644 index 00000000..e4891400 --- /dev/null +++ b/Timeline/Models/Validation/UsernameValidator.cs @@ -0,0 +1,45 @@ +using System.Linq; +using System.Text.RegularExpressions; + +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, out string message) + { + if (value.Length == 0) + { + message = "An empty string is not permitted."; + return false; + } + + if (value.Length > 26) + { + message = $"Too long, more than 26 characters is not premitted, found {value.Length}."; + return false; + } + + foreach ((char c, int i) in value.Select((c, i) => (c, i))) + if (char.IsWhiteSpace(c)) + { + message = $"A whitespace is found at {i} . Whitespace is not permited."; + return false; + } + + var match = _regex.Match(value); + if (!match.Success) + { + message = "Regex match failed."; + return false; + } + + message = ValidationConstants.SuccessMessage; + return true; + } + } +} -- cgit v1.2.3