...

View Full Version : Could someone analyze this script and tell me what's wrong with it?



NanakiXIII
12-20-2003, 07:23 PM
<html>
<head>
<script language="javascript">
function validate(email)
{
if ((email.indexOf("@") != 1) || (email.indexOf(".") < 1))
{
alert ("Invalid")
}
else
{
alert ("Valid")
}
}
</script>
</head>
<body>
<form name="form1">
<input type="text" name="email" value="Enter E-Mail Address">
<input type="button" name="submit" value="Validate" onClick="validate(email.value)">
</form>
</body>
</html>


There are no errors but it gives an "Invalid" alert when I enter a valid address. So I suppose there is something wrong with



if ((email.indexOf("@") != 1) || (email.indexOf(".") < 1))


But I can't figure out what. I'm not a programmer of any kind so please bare with me.

nolachrymose
12-20-2003, 07:30 PM
Try this:


if ((email.indexOf("@") == -1) || (email.indexOf(".") == -1))

Hope that helps!

Happy coding! :)

NanakiXIII
12-20-2003, 07:35 PM
Thanks, it works now. But could you tell my why it works? I wrote this because I'm learning Javascript and didn't understand the tutorial I was following.

nolachrymose
12-20-2003, 07:44 PM
indexOf() method returns the first character in a string that you search for in a whole string, and since the first character is at place 0, if the value is 0, then the string exists in the function starting at character one. It returns a value of -1 if the string does not exist in the large one. So, the line says:


if ((email.indexOf("@") != 1) || (email.indexOf(".") < 1))

If the "@" symbol is not the second character, and the "." character is the first character in the string, or not in the strnig.

Hope that helps!

Happy coding! :)

NanakiXIII
12-20-2003, 07:52 PM
I see. I though indexOf() returned the number of times the part in (parentheses) was found in the string. Thanks. I'm not sure what you mean by "then the string exists in the function starting at character one" though. And what is "the large one"?

nolachrymose
12-20-2003, 09:54 PM
"then the string exists in the function starting at character one" is a reference to when indexOf() method returns a value of 0 (which is false, normally, in JavaScript). The large one is a reference to the entire you are searching with the smaller string. For instance:


var bigStr = "I went to the parade to see the floats.";
alert(bigStr.indexOf("parade"));

"parade" is the little string, and "I went to the parade to see the floats." is the big string.

Hope that helps!

Happy coding! :)

NanakiXIII
12-21-2003, 12:30 AM
Oh right, I understand now. Thanks.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum