【发布时间】:2016-08-05 07:43:28
【问题描述】:
我想验证我的电话号码,并且对于每个无效的情况,我想收到另一条错误消息:
所以,我的验证规则:
- 只有 9 位数字 -> 错误消息 = “错误消息 1”
- 数字不能与相同的数字,例如 222222222 > 错误 message = "错误信息 2"
- 不能是像'123456789'这样的字符串>错误消息=“错误消息3”
- 不能以 0 开头 > 错误消息 =“错误消息 4”
我的电话属性:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MyPhoneAttribute : RegularExpressionAttribute
{
private const string myRegex = @"^([0-9]{9}){0,1}$";
public MyPhoneAttribute () : base(myRegex )
{
ErrorMessage = "default error message";
}
public override bool IsValid(object value)
{
if (string.IsNullOrEmpty(value as string))
return true;
if (value.ToString() == "123456789")
{
return false;
}
if (Regex.IsMatch(value.ToString(), @"^([0-9])\1*$"))
{
return false;
}
return Regex.IsMatch(value.ToString(), @"^([0-9])\1*$");
}
}
【问题讨论】:
-
那么,问题是什么?
-
我不知道如何创建带有不同错误消息的验证规则。
-
@Wenson 我想拥有自己的属性
-
var 模式 = /^\d{9}$/ 九位数
标签: c# asp.net .net validation data-annotations