0

I'm using jQuery to validate form elements on an MVC form and this is my regular expression to validate zip codes:

^(\d{5})|(\d{5}-\d{4})$

It validates a 5-digit zip code just fine, but the red box around the text box input element remains—er, comes back—when I add a hyphen and 4 more digits.

Why?

4

2 回答 2

4

以下 RegRxp 中的括号是错误的:

^(\d{5})|(\d{5}-\d{4})$

这就像说 match^\d\d\d\d\d或 match \d\d\d\d\d-\d\d\d\d$。它错误地匹配12345xx98765-4321。请改用以下内容:

^(\d{5}|\d{5}-\d{4})$
于 2013-02-14T18:17:53.877 回答
0

当我更仔细地查看生成的 HTML 时,我注意到它有 data-val-length-max="9"。这是模型中的一个属性。我把它改成了 10,瞧!

为了让验证正常工作并且仍然将未格式化的数字传递给数据库,我只是从模型的 getter 中返回它:

_zip.Replace("-", string.Empty)
于 2013-02-14T19:17:40.767 回答