using System;
using System.Text.RegularExpressions;
namespace Swan.Validators
{
///
/// Regex validator.
///
[AttributeUsage(AttributeTargets.Property)]
public class MatchAttribute : Attribute, IValidator
{
///
/// Initializes a new instance of the class.
///
/// A regex string.
/// The error message.
/// Expression.
public MatchAttribute(string regex, string errorMessage = null)
{
Expression = regex ?? throw new ArgumentNullException(nameof(regex));
ErrorMessage = errorMessage ?? "String does not match the specified regular expression";
}
///
/// The string regex used to find a match.
///
public string Expression { get; }
///
public string ErrorMessage { get; internal set; }
///
public bool IsValid(T value)
{
if (Equals(value, default(T)))
return false;
return !(value is string)
? throw new ArgumentException("Property is not a string")
: Regex.IsMatch(value.ToString(), Expression);
}
}
///
/// Email validator.
///
[AttributeUsage(AttributeTargets.Property)]
public class EmailAttribute : MatchAttribute
{
private const string EmailRegExp =
@"^(?("")("".+?(?
/// Initializes a new instance of the class.
///
/// The error message.
public EmailAttribute(string errorMessage = null)
: base(EmailRegExp, errorMessage ?? "String is not an email")
{
}
}
///
/// A not null validator.
///
[AttributeUsage(AttributeTargets.Property)]
public class NotNullAttribute : Attribute, IValidator
{
///
public string ErrorMessage => "Value is null";
///
public bool IsValid(T value) => !Equals(default(T), value);
}
///
/// A range constraint validator.
///
[AttributeUsage(AttributeTargets.Property)]
public class RangeAttribute : Attribute, IValidator
{
///
/// Initializes a new instance of the class.
/// Constructor that takes integer minimum and maximum values.
///
/// The minimum value.
/// The maximum value.
public RangeAttribute(int min, int max)
{
if (min >= max)
throw new InvalidOperationException("Maximum value must be greater than minimum");
Maximum = max;
Minimum = min;
}
///
/// Initializes a new instance of the class.
/// Constructor that takes double minimum and maximum values.
///
/// The minimum value.
/// The maximum value.
public RangeAttribute(double min, double max)
{
if (min >= max)
throw new InvalidOperationException("Maximum value must be greater than minimum");
Maximum = max;
Minimum = min;
}
///
public string ErrorMessage => "Value is not within the specified range";
///
/// Maximum value for the range.
///
public IComparable Maximum { get; }
///
/// Minimum value for the range.
///
public IComparable Minimum { get; }
///
public bool IsValid(T value)
=> value is IComparable comparable
? comparable.CompareTo(Minimum) >= 0 && comparable.CompareTo(Maximum) <= 0
: throw new ArgumentException(nameof(value));
}
}