using System;
using System.Text.RegularExpressions;
using Unosquare.Swan.Abstractions;
namespace Unosquare.Swan.Attributes {
///
/// 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) {
this.Expression = regex ?? throw new ArgumentNullException(nameof(this.Expression));
this.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 Boolean IsValid(T value) => Equals(value, default(T))
? false
: !(value is String)
? throw new ArgumentException("Property is not a string")
: Regex.IsMatch(value.ToString(), this.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 Boolean 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(Int32 min, Int32 max) {
if(min >= max) {
throw new InvalidOperationException("Maximum value must be greater than minimum");
}
this.Maximum = max;
this.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");
}
this.Maximum = max;
this.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 Boolean IsValid(T value)
=> value is IComparable comparable
? comparable.CompareTo(this.Minimum) >= 0 && comparable.CompareTo(this.Maximum) <= 0
: throw new ArgumentException(nameof(value));
}
}