-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathPasswordAttribute.cs
More file actions
54 lines (42 loc) · 2.23 KB
/
Copy pathPasswordAttribute.cs
File metadata and controls
54 lines (42 loc) · 2.23 KB
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
47
48
49
50
51
52
53
54
using System.ComponentModel.DataAnnotations;
using OpenShock.Common.Constants;
namespace OpenShock.Common.DataAnnotations;
/// <summary>
/// An attribute used to validate whether a password is valid.
/// </summary>
/// <remarks>
/// Inherits from <see cref="ValidationAttribute"/>.
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public sealed class PasswordAttribute : ValidationAttribute
{
/// <summary>
/// Example value used to generate OpenApi documentation.
/// </summary>
private const string ExampleValue = "user@example.com";
private const string ErrMsgCannotBeNull = "Password cannot be null";
private const string ErrMsgMustBeString = "Password must be a string";
private const string ErrMsgTooShort = "Password is too short";
private const string ErrMsgTooLong = "Password is too long";
private const string ErrMsgCannotStartOrEndWithWhiteSpace = "Password cannot start or end with whitespace";
/// <summary>
/// Indicates whether validation should be performed.
/// </summary>
public bool ShouldValidate { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PasswordAttribute"/> class with the specified validation behavior.
/// </summary>
/// <param name="shouldValidate">True if validation should be performed; otherwise, false.</param>
public PasswordAttribute(bool shouldValidate) => ShouldValidate = shouldValidate;
/// <inheritdoc/>
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (!ShouldValidate) return ValidationResult.Success;
if (value is null) return new ValidationResult(ErrMsgCannotBeNull);
if (value is not string password) return new ValidationResult(ErrMsgMustBeString);
if (password.Length < HardLimits.EmailAddressMinLength) return new ValidationResult(ErrMsgTooShort);
if (password.Length > HardLimits.EmailAddressMaxLength) return new ValidationResult(ErrMsgTooLong);
if (password.Trim().Length != password.Length) return new ValidationResult(ErrMsgCannotStartOrEndWithWhiteSpace);
return ValidationResult.Success;
}
}