views:

92

answers:

2

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 = " Invalid 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() %>
<% }); %>
+2  A: 

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.

Kobi
I did have the start and end anchors before, took them out and forgot to say I tried them. I have found that it was fighting with my mask plugin. +1 for pointing out the anchors tho, I should have mentioned I used them.
gmcalab
+1  A: 

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

gmcalab