我已经添加了以下自定义数据注释验证我的代码为我的文字区域(只允许有效的电子邮件ID)自定义数据标注工作不
public class ValidateEmails : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string[] commaLst = value.ToString().Split(',');
foreach (var item in commaLst)
{
try
{
System.Net.Mail.MailAddress email = new System.Net.Mail.MailAddress(item.ToString().Trim());
}
catch (Exception)
{
return new ValidationResult(ErrorMessage = "Please enter valid email IDs separated by commas;");
}
}
}
return ValidationResult.Success;
}
}
型号:
public class BuildModel
{
public Int64 ConfigID { get; set; }
[Required(ErrorMessage = "Please select a stream!")]
public string StreamName { get; set; }
[Required(ErrorMessage = "Please select a build location!")]
public string BuildLocation { get; set; }
public string Type { get; set; }
public bool IsCoverity { get; set; }
[ValidateEmails(ErrorMessage = "NOT VALID !!!")]
public string EmailIDsForCoverity { get; set; }
}
当我运行我的应用程序并在文本区域中输入无效的字符串时,断点会在验证内部发生。但是,提交行为仍然会发生。
实际上,我有一个引导模式窗体,我在其中进行验证。点击提交按钮,内置的自定义验证,如“必需”,效果很好。但是,我的自定义数据注释验证不起作用。我在这里做什么错了?
你的'Model.IsValid'在你的行动检查? – DavidG
你可以使用'RegularExpression'验证器为此和正则表达式为逗号分隔验证是'(([[A-ZA-Z0-9 _ \ - \。] +)@((\ [[0-9] {1,3 } \ [0-9] {1,3} \ [0-9] {1,3} \)|。。。(([A-ZA-Z0-9 \ - ] + \)+))( (\ s *; \ s * | \ s * $))* '请检查[a-zA-Z] {2,4} | [0-9] {1,3})这个答案](https://stackoverflow.com/a/9809636/2534646)获取更多信息 – Curiousdev
你的属性需要实现'IClientValidatable',如果你需要写脚本来将规则添加到'$ .validator'想要客户端验证。 –