Tutorial :javascript validate zip regular expression



Question:

Thanks guys. I take your advice and modify the script as following. Now it seems working.

<script src="jquery-1.4.2.min.js" type="text/javascript"></script>     <script>  $(function(){  var pat=/^[0-9]{5}$/;  if ( !pat.test(   $('#zip').val()   ) )  {$('#zip').after('<p>zip is invalid</p>');}  })  </script>    zip (US only) <input type="text" name='zip' id='zip' maxlength="5">  


Solution:1

.val needs to be .val()
and use .after() or .before() and not .append()

var pattern = /^[0-9]{5}$/;  if (!pattern.test($('#zip').val())) {    $('#zip').after('<p>zip is invalid</p>');  }  


Solution:2

zip is invalid should be enclosed in quotes

and .val needs to be .val()

<script>    pattern=/^[0-9]{5}$/;    if (!pattern.test( $('#zip').val() ) )     {      $('#zip').val($('<p>',{html: "zip is invalid"}));    }  </script>  


Solution:3

Space it out so you can see what's wrong..

pattern=/^[0-9]{5}$/;  if (     !pattern.test(   $('#zip').val()  )   )  {      $('#zip').after(           $('<p>',{html: "zip is invalid"})      );  }  

val() and "zip is valid". Also, the var is useless unless within a function scope.

(function() {      var pattern=/^[0-9]{5}$/;      if (         !pattern.test(   $('#zip').val()  )       )      {          $('#zip').after(               $('<p>',{html: "zip is invalid"})          );      }  })();  

Now pattern is local to that function only and nothing else. In CMS's example it's still a global unless you're taking the snippet and using it in an actual function.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »