why does this regex work outside of a javascript function but not inside of it?
Okay so I'm kind of new to regexps in general, let alone in Javascript.
I am trying to work on a form validation project and I found a site where they have a list of useful sample regexps for various things here which has a few for email validation, which is what I'm attempting at the moment. Anyway, following this example for form validation on w3schools I was able to get it working properly using their example and the regexp works outside of the javascript function, but for some reason when I call it inside the function it returns a value of undefined. Here's my 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 an email address") == false)
{
email.focus();
return false;
}
}
}
</script>
</head>
<body>
<form action="#" me开发者_开发技巧thod="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... so the alert in the script tags inside the body works just fine.
I've done numerous tests inside the javascript function itself and checked various things:
- the type of 'value' is String
- the function returns 'undefined' when called inside the javascript
- the regex itself works fine as it will return true when the proper formatting is entered in the script tags below
So what could the issue be? I am confused.
The problem is that pattern
refers to field.pattern
(an HTML5 attribute) because you're using it inside the with()
, and that's a string, not your regex. If you called it something else like pattern1
, it would work fine.
That being said, don't use with
in the first place, and you won't have these issues :)
The non-with
version looks like 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 an email address") == false) {
form.email.focus();
return false;
}
}
You can test it out here.
精彩评论