Discuss Can someone please explain this js code in the JavaScript Development forum on Dev Shed. Can someone please explain this js code JavaScript Development forum discussing JavaScript and DHTML, AJAX, and issues such as coding cross-browser JavaScript.
Posts: 153
Time spent in forums: 1 Day 13 h 5 m 54 sec
Reputation Power: 4
Other - Can someone please explain this js code
Hello all,
I'm new and still learning. while i understand most of this script, im wondering if you good folks could please fill in the blanks.
Code:
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
the bit im kind of struggling with is the 'if' line:
I understand that the code is evaluating an HTML form, and checking whether its been filled in correctly, im not sure that i am reading it right.
I understand, i think, that:
1. The atpos cannot be the first in the email address because of the atpos<1,
2. The dotpos cannot be before the atpos owing to dotpos<atpos, but what does the +2 mean?
Also,
3. what is the +2 do here: dotpos+2>=x.length ...?
Posts: 7,939
Time spent in forums: 2 Months 9 h 12 m 42 sec
Reputation Power: 7053
atpos < 1
requires there to be at least one character before the @ symbol in the email address. If atpos is 0 it means the string starts with @, if atpos is -1 it means the string does not contain @.
+2 adds 2
dotpos < atpos+2
requires there to be at least one character between the @ sign and the dot. If dotpos and atpos were equal, it would mean that the same character is both an @ sign and a dot (which is not actually possible). If dotpos were less than atpos, it would mean the dot appears before the @ sign. If dotpos were equal to atpos+1 it would mean the dot immediately follows the @ sign.
dotpos+2 >= x.length
by similar logic, this requires there to be at least one character after the dot
Posts: 863
Time spent in forums: 5 Days 16 h 50 m 17 sec
Reputation Power: 1185
Quote:
Originally Posted by E-Oreo
dotpos+2 >= x.length
by similar logic, this requires there to be at least one character after the dot
It means that the dot must be followed by at least two characters. (There are no top level domains with less than two characters.) More literally it means there must be two characters between the dot and the end of the string.
__________________ Don't like me? Click it.
Scripting problems? Windows questions? Ask the Windows Guru!
Also did your question include any URLs? New users are restricted from posting URLs until they have made 5 posts. You may need to get around this by leaving out the "http://" and putting a space before each ".". Yes this rule is annoying, but the administrators say it's necessary for limiting spam.
__________________
Spreading knowledge, one newbie at a time. I'm available for hire at Dynamic Site Solutions.