开发者

xVal and Regular Expression Match

I am using xVal to validate my forms in asp.net MVC 1.0

Not sure why my regular expression isn't validating correctly.

  • It does NOT validate with an empty value
  • It does NOT validate with the value of "1", "12", "123", or "1234"
  • It validates with the value of "12345"
  • It validates with the value of "12345 "
  • It validates with the value of "12345 -"
  • It validates with the value of "12345 -1"
  • It validates with the value of "12345 -12" ... etc

For a zip code I expect one of the two patterns:

12345 or 12345 -1234

Here are the two regex I tried:

(\d{5})((( -)(\d{4}))?)

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

Here is my MetaData class for xVal

[MetadataType(typeof(TIDProfileMetadata))]
public class TIDProfileStep
{
   public class TIDProfileMetadata
   {
       [Required(ErrorMessage = " [Required] ")]
       [RegularExpression(@"(\d{5})|(\d{5} -\d{4})", ErrorMessage = " Inv开发者_JAVA技巧alid Zip ")]
       public string Zip { get; set; }
   }
}

Here is my aspx page:

<% Html.BeginForm("Edit", "Profile", FormMethod.Post); %>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
   <td>
      <h6>Zip:</h6>
   </td>
   <td>
      <%= Html.TextBox("Profile.Zip")%>
   </td>
</tr>
<tr>
   <td>
      <input type="submit"/>
   </td> 
</tr>
</table>
<% Html.EndForm(); %>

<% Html.Telerik().ScriptRegistrar()
        .OnDocumentReady(() =>
   { %>
   <%= Html.ClientSideValidation<TIDProfileStep>("Profile").SuppressScriptTags() %>
<% }); %>


You're missing the start and end anchors:

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

Without these you allow partial matching. The regex matches the string 12345 -1 by \d{5}: 12345-1, and validates it.


I failed to mention that I was using a mask plugin for my input field. The mask plugin can be found here.

So on the text box if I were to fill in only the first 5 digits and then tab to the next field is would validate as false due to the mask plugin I have used. The mask plugin, puts in an underscore character for empty possiblities.... So for example:

_____ -____ would be the mask that it would put in the empty field on focus. If I fill in the first 5 digits I would have:

12345 -____

Then if I tab to the next field, the -____ is removed, but the input field needs to be re-validated onblur.

So what I did was re-validate the input field on blur and now it works.

$('#Zip').blur(function() {
        $(this).validate();
});

I use this regex ^\d{5}( -\d{4})?$

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜