Javascript form & email validation not working

Hi all,

I am trying to develop a form with email validation but i am recieving an error which is this

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB6.3; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)
Timestamp: Tue, 13 Apr 2010 11:48:06 UTC

Message: Syntax error
Line: 4
Char: 39
Code: 0
URI: file:///C:/Users/williamtosh/Desktop/javascriptvalid.html

This is my code


<script language = "Javascript">
function checkdata()
	{
		if(document.form-validate.name.value="")
		{
			alert("You Must enter a name");
			return false;
		}
		else if(document.form-validate.email.value==""||document.form-validate.email.value.length<6)
		{
			alert("You havnt entered in an valid email address!");
			return false;
		}
		else if(document.form-validate.email.value.indexOf("@")==-1 || document.form-validate.email.value.indexOf(".")==-1)
		{
			alert("Thats not a valid email address or doesnt exist!");
			return false;
		}
		else
		{
			alert("Thank you!");
			return true;
		}

	}
</script>
<form name="form-validate" method="post" action="" onsubmit="return checkdata();">
	<input type="text" name="name" />
    <input type="text" name="email" />
    <input type="submit" name="reg" value="Done">
</form>

Why do i get that error above?

can anyone tell me what am i doing wrong?

Thanks,William

I never use names on forms, I guess because it was deprecated in XHTML even though I write in HTML4…

Your main error is likely the assignment = you use in the if. You know the difference between = and == and === right?

When you’re doing an if to ask if something equals something, you can’t use = because now you’re not asking, you’re telling.

Anyway, you certainly shouldn’t need a name on the form. Let’s try with an id without hyphens just for the lawlz (and let’s make your form VALID by wrapping the inline inputs inside a block (fieldset)):


<form id="[b]formValidate[/b]" method="post" action="" onsubmit="return checkdata();">
[b]<fieldset>
    <legend>Sign up!</legend>[/b]
	<input type="text" name="[b]user[/b]name" />
      <input type="text" name="email" />
    <input type="submit" name="reg" value="Done">
[b]</fieldset>[/b]
</form>


function checkdata() {
    var nameInput = document.forms["formValidate"]["username"],
        emailInput = document.forms["formValidate"]["email"],
        emailPattern = /^[\\w\\.\\-\\_]+@([\\w\\-\\_]+\\.)+[a-zA-Z]{2-6}$/; 

    if(nameInput.value == "") {
        alert("You Must enter a name");
        return false;
    }
    var emailCheck = emailPattern.test(emailInput.value));
    if(!(emailCheck)) {
        alert("You haven't entered in an valid email address!");
        return false;
    }

etc...

You had it right in the email one (==) but I think I’d also use a single line of regex for the email… in one line you could check if anything was typed in, and if it matched the particular pattern you wanted… if it matches, it’s a go. If anything doesn’t match, whether it’s the email address not being long enough, or not having an @, or whatever, then it fails either way.

Ok, I didn’t test that regex: I dunno if I really have to comment out _ like I did, and I forgot if JS can do the ranges for characters {2-6} but if it does it’ll accept everything from .nl to .museum (and likely all sorts of crap too)…
also not sure if I did the if not thing right either… doesn’t matter, was just something I wanted to try.

I changed the name of name to username just to make sure some other weird error wouldn’t appear in my example, but I think you can prolly keep the - in the form id/name and keep name as name in the input.

hm WRONG

should be
if(!emailCheck) {

: )

or just not use that emailCheck var at all

if(!emailPattern.test(emailInput.value)) {

Try it like this script:
http://www.elated.com/articles/form-validation-with-javascript/

But modify it like this with an ID in the submit <input> tag:

<form name="form-validate" method="post" action="">
	<input type="text" name="name" />
    <input type="text" name="email" />
    <input type="submit" name="reg" value="Done" id="theclicker">
</form>

Try to invoke it by something like this, catch the ID theclicker:

function restValidation() {
    valid = true;
    if ( document.form-validate.name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }
    return valid;
}

function doValidation(){
var send = document.getElementById('theclicker');
send.onclick = restValidation;
}
  
window.onload = doValidation;

With multiple field validations, you can do it with this way || and check every time:

if ( document.formname.fieldname1.value == “” || document.formname.fieldname2.value == “” || document.formname.fieldname3.value == “” ) {

But can you do it like this aswel, by checking it once at the end ?

if ( document.formname.fieldname1.value || document.formname.fieldname2.value || document.formname.fieldname3.value == “” ) {

Haven’t tested yet, but want to know what’s the best or most efficient approach

^the long OR approach was I think working for the OP. However what your last version does is ask if the eval (document.formname.fieldname1.value) is true or not. (oh weird the computer I’m on doesn’t have a pipe key! I’ll use LLs!)
ll checks to see if something IS true or false. I don’t think it’s looking at the equivalent value of .value, I think it’s looking to see if value itself is true (exists). I wonder what it would do. The part at the end is looking to see if the evaluation is false or true. .value == “” is true if value is an empty string.

But when you start repeating yourself like that (you’re checking one to see if it’s empty… then checking the next to see if it’s empty… then checking the next to see if it’s empty… and that’s when the bulb should go off in your brain (even in a non-programmer like me) hey, there’s a simpler way somewhere.

In the email check the OP has, s/he’s checking for lots of things individually for one input. So doing one check to see if the regex matches is just less writing and likely less thinking involved, which I’m personally a fan of : )

In a situation where you’re checking lots of inputs simply to see if they’re empty, loop through them and compare (everyone[i].value == “”) instead of using ORs. I don’t know that it’s faster, but I know I’d prefer to write it that way. Mostly because when I think I understand it (it’s not rocket surgery) I get tripped up when the whole left-right comparing thing stops and only checks one side when I keep thinking it’s going to check both sides.
Then again that’s likely just my not being a programmer yet.

I know you can check with a for loop or something like that, but what if you don’t have to check every field. If not every field in your form has a mark that it’s obligatory to fill in.
Anyway, I’m not good in loops and other stuff, for me it’s more simpler to do it this way at the moment. I’m still a n00b in Javascript.

Also, the way you declare your variables takes the same amount of space as checking them…
var nameInput = document.forms[“formValidate”][“username”],

Also, the way you declare your variables takes the same amount of space as checking them…
var nameInput = document.forms[“formValidate”][“username”],

Mostly I do that so I can just use them wherever istead of retyping " document.forms[“formValidate”][“username”]" everywhere (if I’m going to type it more than twice) “nameInput” is shorter and I’m lazy.

What if you have 30 fields you need to check if they’re empty (out of say a group of 40 inputs)?

And, what if one is empty, in the middle? I’m thinking once the ORs hit a true, they stop checking the rest, right?


if ( document.formname.fieldname1.value == "" ||
 document.formname.fieldname2.value == "" ||
 document.formname.fieldname3.value == "" ||
 document.formname.fieldname4.value == "" ||
 document.formname.fieldname5.value == "" ||
 document.formname.fieldname6.value == "" ||
 document.formname.fieldname7.value == "" ) {

So if field 3 IS empty, then something is true, and the code in the body of the if runs… but you also want to know if 4, 5, 6 or 7 are also empty, to tell the user “you missed questions 3, 4, 5, 6, and 7”. I suppose you could alert the user of one, make them fix and resend, alert them to the next one, make them fix and resend… on our forms, we decided, foo, peope are lazy and hate filling out (non-trivial) forms, so when people submit we send back all the errors they made… they can fix all of them one time and resend. Plus I’d be embarrassed to have more than 2 or three ORs in an if statement.

But, I’m also a n00b in JS, and what’s great is we can screw each other up with our half-knowledge! : )

So of course, that means a real guru has to step in and righteously mend our broken ways (mrhoooooo)…

ive got it sorted now thanks guys i found out it wasnt the on-submit button wasnt working with my joomla registeration so i just moved it to the submit button and it worked.

William: good to hear, but you will want to fix that = to == in your first if statement : )

Sorry to bother once more.
As I’m still doing it the other way :p, I still have a question.

Right here in this tutorial, they write it like this:



function restValidation() {
    valid = true;
    if ( document.form-validate.name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }
    return valid;
}
 
function doValidation(){
var send = document.getElementById('theclicker');
send.onclick = restValidation;
}
  
window.onload = doValidation;

Is it possible to leave those “valid” stuff out? Because without it, it works aswel:


function restValidation() {
    if ( document.form-validate.name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
     }
}
 

And second, if used the valid stuff in, shouldn’t it be declared first with
var valid = true;

As I’m still doing it the other way

Your way is nicer than the OPs because it keeps the slimy JS away from the HTML, which is preferred.

Functions Return Stuff, or Do Stuff, or both. In the tutorial, they’re explicitly returning “valid” (returning true or false). With form validation, you’re returning true (submit the form) or false (don’t submit the form), to the browser.

If you don’t explicitly return something, then it silently returns undefined and this is generally when you’re using a form to Do Something rather than Return something. Return also stops a function in its tracks.

They seem to want the function to explicitly tell the browser whether or not to do the submit. However, if you don’t say “return false”, by default the browser will try to do what it does (similar if you have an onclick event on an anchor, if you want the script to do everything and want to block the browser’s default anchor action, you return false to stop that). I don’t know if every single browser does this though, I haven’t messed with JS per browser very much.

Me, I’d prolly keep it in because if I’m bothering to dick with someone’s form input, I might as well pedantically state whether or not they shall pass the gate.

And second, if used the valid stuff in, shouldn’t it be declared first with
var valid = true;

They should have used var, yes. Always always use var, even when it seems like you’re eating pizza and french fries with a fork and knife, do it. I even use var inside the conditionals of a for loop.