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="#" 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... 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.