why does this regex work outside of a javascript function but not inside of it? -
okay i'm kind of new regexps in general, let alone in javascript.
trying work on form validation project , found site have list of useful sample regexps various things here has few email validation, i'm attempting @ moment.
anyway, following example form validation on w3schools able working using example , regexp works outside of javascript function, reason when call inside function returns value of undefined.
here's code:
<html> <head> <title>formzz validate-jons</title> <script type="text/javascript"> pattern = new regexp("^[0-9a-za-z]+@[0-9a-za-z]+[\.]{1}[0-9a-za-z]+[\.]?[0-9a-za-z]+$"); function valid8email(field, txt) { with(field) { //at_pos = value.indexof('@'); //dot_pos = value.lastindexof('.'); if(!pattern.test(value)) //at_pos < 1 || (dot_pos - at_pos) < 2) { alert(txt); return false; } else { return true; } } } function valid8(form) { with(form) { if(valid8email(email, "you must enter email address") == false) { email.focus(); return false; } } } </script> </head> <body> <form action="#" method="post" onsubmit="return valid8(this)"> email: <input type="text" name="email" size="30" /> <input type="submit" value="clicky-click" /> </form> <script type="text/javascript"> alert(pattern.test("")); </script> </body> </html>
okay... alert in script tags inside body works fine.
i've done numerous tests inside javascript function , checked various things:
- the type of 'value' string
- the function returns 'undefined' when called inside javascript
- the regex works fine return true when proper formatting entered in script tags below
so issue be? confused.
the problem pattern
refers field.pattern
(an html5 attribute) because you're using inside with()
, , that's string, not regex. if called else pattern1
, it work fine.
that being said, don't use with
in first place, , won't have these issues :)
the non-with
version looks this:
var pattern = new regexp("^[0-9a-za-z]+@[0-9a-za-z]+[\.]{1}[0-9a-za-z]+[\.]?[0-9a-za-z]+$"); function valid8email(field, txt) { if (!pattern.test(field.value)) { alert(txt); return false; } else { return true; } } function valid8(form) { if (valid8email(form.email, "you must enter email address") == false) { form.email.focus(); return false; } }
Comments
Post a Comment