0

I'm attempting to do validation on form fields via MVCs regular expression attributes. But it seems that no matter what regular expression I use, the validation only works on the server side, but not in the browser.

The code I am using for the validation is:

[DisplayName("Email Address")]
[Required]
[RegularExpression(@"^[a-zA-Z0-9\.-]*@[a-zA-Z0-9\.]*\.[a-zA-Z\.]{2,6}$", ErrorMessage = "Valid email required.")]
public string emailAddress { get; set; }

The regular expression will fail validation with "asd", "asd@" but it starts to pass validation at "asd@asd" when it shouldn't. Pasting the regular expression into http://regexpal.com/ will show that it should only work with full emails.

Screenshots: http://puu.sh/2P05x.png

If it helps, this is being used in a Kendo UI grid edit pop up.

tereško
  • 58,060
  • 25
  • 98
  • 150
TLS
  • 3,585
  • 1
  • 19
  • 20
  • Might want to check out this answer from a very similar question: http://stackoverflow.com/a/8989157/534109 – Tieson T. May 08 '13 at 01:00
  • I saw that a while ago, that alone doesn't actually do any client side validation. ie: it will still let me type in jargon, rather than preventing any input other than valid email addresses. – TLS May 08 '13 at 01:09

2 Answers2

0

On your model:

[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,4}\.[0-9]{1,4}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "invalid.")]

and make sure jquery.validate.min.js and jquery.validate.unobtrusive.min.js are referenced in your page

and finally in your web.config

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

Or if you want to do it using JS:

^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,4}\.[0-9]{1,4}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
Karim
  • 150
  • 6
  • I have seemed to have stumbled accross some evidence that this is a KendoUI issue (either that or it is a malformed regex). Using that regex gets a javascript error when i attempt to run it. `'Uncaught SyntaxError: Invalid regular expression: /^(?:^(<>?)$)$/: Range out of order in character class'` in kendo.aspnetmvc.min.js:9 – TLS May 08 '13 at 02:11
  • I am not familiar with kendo but it seems you are right and there is an inconsistency between this regex and kendo. you can debug it using Firebug but it wont be easy – Karim May 08 '13 at 02:21
0

Apparently this is a currently known bug in the version of KendoUI i was using. Im not sure if there is an applicable update for it yet. More information about it here, http://www.kendoui.com/forums/mvc/general-discussions/regular-expression-validator-not-working-in-grid-popup.aspx

TLS
  • 3,585
  • 1
  • 19
  • 20