在模型上使用Data Annotations时,我遇到了为客户端验证而发出的JavaScript的问题。这是一个模型的示例,它可以很好地处理两个必填字段,然后是发出的JavaScript:
public class LoginUserViewModel
{
[Required(ErrorMessage = "Email required")]
public string EmailAddress { get; set; }
[Required(ErrorMessage="Password required")]
public string Password { get; set; }
}
}
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"EmailAddress","ReplaceValidationMessageContents":true,"ValidationMessageId":"form0_EmailAddress_validationMessage","ValidationRules":[{"ErrorMessage":"Email required","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"Password","ReplaceValidationMessageContents":true,"ValidationMessageId":"form0_Password_validationMessage","ValidationRules":[{"ErrorMessage":"Password required","ValidationParameters":{},"ValidationType":"required"}]}],"FormId":"form0","ReplaceValidationSummary":false});
//]]>
只要在EmailAddress字段(正则表达式属性)上放置另一个属性,JavaScript就不再发出任何规则。请注意,在下面的JavaScript中,只有一个空数组,其中应该是规则。这是改变和脚本。有什么想法吗?
public class LoginUserViewModel
{
[Required(ErrorMessage = "Email required")]
[RegularExpression(@"^[a-z0-9]+([-+\.]*[a-z0-9]+)*@[a-z0-9]+([-\.][a-z0-9]+)*{2,4}$", ErrorMessage = "Invalid email format")]
public string EmailAddress { get; set; }
[Required(ErrorMessage="Password required")]
public string Password { get; set; }
}
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"EmailAddress","ReplaceValidationMessageContents":true,"ValidationMessageId":"form0_EmailAddress_validationMessage","ValidationRules":[]},{"FieldName":"Password","ReplaceValidationMessageContents":true,"ValidationMessageId":"form0_Password_validationMessage","ValidationRules":[{"ErrorMessage":"Password is required.","ValidationParameters":{},"ValidationType":"required"}]}],"FormId":"form0","ReplaceValidationSummary":false});
//]]>
当添加新属性时,是什么导致规则消失?
谢谢!
答案 0 :(得分:6)
经过进一步调查后,问题是你的正则表达式被破坏了,因为你已经指定了两个背对背的量词:
parsing "[a-z0-9]+([-+\.]*[a-z0-9]+)*@[a-z0-9]+([-\.][a-z0-9]+)*{2,4}"
- Nested quantifier {.
所有规则似乎消失的原因是因为CLR吞噬了属性构造函数中的异常,只是告诉你“对不起,这里没有属性。”