Jo Shields 3c1f479b9d Imported Upstream version 4.0.0~alpha1
Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
2015-04-07 09:35:12 +01:00

26 lines
1.1 KiB
C#

namespace System.ComponentModel.DataAnnotations {
using System;
using System.ComponentModel.DataAnnotations.Resources;
using System.Text.RegularExpressions;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class PhoneAttribute : DataTypeAttribute {
// see unit tests for examples
private static Regex _regex = new Regex(@"^(\+\s?)?((?<!\+.*)\(\+?\d+([\s\-\.]?\d+)?\)|\d+)([\s\-\.]?(\(\d+([\s\-\.]?\d+)?\)|\d+))*(\s?(x|ext\.?)\s?\d+)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
public PhoneAttribute()
: base(DataType.PhoneNumber) {
ErrorMessage = DataAnnotationsResources.PhoneAttribute_Invalid;
}
public override bool IsValid(object value) {
if (value == null) {
return true;
}
string valueAsString = value as string;
return valueAsString != null && _regex.Match(valueAsString).Length > 0;
}
}
}