aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Models/Validation/UsernameValidator.cs
blob: ecc3b5b398f1758062c36c2a6197c39fd9a95c38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using Microsoft.Extensions.Localization;
using System.Linq;
using System.Text.RegularExpressions;

namespace Timeline.Models.Validation
{
    public class UsernameValidator : Validator<string>
    {
        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)
        {
            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;
        }
    }
}