[Serializable]
public abstract class RegExRestrictedString : IEquatable<RegExRestrictedString> {
string internalValue;
public RegExRestrictedString() { }
public virtual RegexOptions Options {
get { return RegexOptions.None; }
}
protected abstract string Pattern { get; }
public string Value {
get { return internalValue; }
set {
Validate(value);
this.internalValue = value;
}
}
private void Validate(string value) {
if (string.IsNullOrEmpty(Pattern)) throw new InvalidOperationException(
);
Regex regEx = new Regex(Pattern, Options);
if (regEx.Matches(value).Count != 1)
throw new InvalidOperationException();
}
public override string ToString() {
return internalValue;
}
public override bool Equals(object obj) {
return (obj is RegExRestrictedString) && Equals((RegExRestrictedString)obj);
}
public override int GetHashCode() {
return internalValue.GetHashCode()^Pattern.GetHashCode()^Options.GetHashCode();
}
public bool Equals(RegExRestrictedString other) {
if (object.ReferenceEquals(other, null)) return false;
return ((Pattern == other.Pattern) && (Value == other.Value)
&& (Options == other.Options));
}
public static bool operator ==(RegExRestrictedString first, RegExRestrictedString second) {
if (object.ReferenceEquals(first, second)) return true;
if (object.ReferenceEquals(first, null) || object.ReferenceEquals(second, null))
return false;
return ((first.Pattern == second.Pattern) && (first.Value == second.Value)
&& (first.Options == second.Options));
}
public static bool operator !=(RegExRestrictedString first, RegExRestrictedString second) {
return !first.Equals(second);
}
}