views:

735

answers:

1

I'm having trouble with the JavaScript being emitted for client side validation when using Data Annotations on a model. Here's a sample of a model that works just fine with two required fields followed by the JavaScript that's emitted:

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});
//]]> 

as soon as I put another attribute on the EmailAddress field, a regular expression attribute, the JavaScript no longer has any rules emitted. Notice in the JavaScript below there is just an empty array where the rules should be. Here's the change and the script. Any ideas?

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});
//]]> 

Any ideas what's causing the rules to disappear when the new attribute is added?

Thanks!

+5  A: 

After further investigation, the problem is that your regular expression is broken, because you've specified two quantifiers back-to-back:

parsing "[a-z0-9]+([-+\.]*[a-z0-9]+)*@[a-z0-9]+([-\.][a-z0-9]+)*{2,4}"
- Nested quantifier {.

The reason all the rules seem to disappear is because the CLR swallows exceptions from attribute constructors and just tells you "sorry, there are no attributes here."

Brad Wilson