MVC validation regex attribute works in C# but not JavaScript

試著忘記壹切 提交于 2019-12-25 02:06:25

问题


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.


回答1:


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})(\]?)$



回答2:


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



来源:https://stackoverflow.com/questions/16430583/mvc-validation-regex-attribute-works-in-c-sharp-but-not-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!