Javascript form validation problem

I am having a problem with validating my form, it works if I only validate 1 field, but if I try to validate more than 1, nothing happens when I click submit

Here is my code:

function validateForm()
{
var x=document.forms[“dform”][“name”].value
if (x==null || x==“”)
{
alert(“Enter Name!”);
return false;
}
}
{
var x=document.forms[“dform”][“selling_1”].value
if (x==null || x==“”)
{
alert(“Enter Selling Name!”);
return false;
}
}

The return statement stops all code after it from being able to execute.

Instead of returning at the first sight of an error, you may want to set a variable at the start called isValid to true, and then set isValid to false when you encounter an error.

At the end of things, you can then return that isValid variable.

thanks! Do you mean like this:

function validateForm()
isValid=true;
{
var x=document.forms[“dform”][“name”].value
if (x==null || x==“”)
{
alert(“Enter Name!”);
isValid= false;
}
}
{
var x=document.forms[“dform”][“selling_1”].value
if (x==null || x==“”)
{
alert(“Enter Selling Name!”);
isValid= false;
}
}

Nearly. No code goes before the function brace, so it should start with:


function validateForm()
{
    isValid=true;
    ...
}

Many of is prefer to put the brace immediately after the function parenthesis, to help prevent such easy mistakes.


function validateForm() {
    isValid=true;
    ...
}

And it should end by returning the isValid variable.


function validateForm() {
    ...
    return isValid;
}

thanks heaps! I tried this, but when I submit the form it doesnt do anything… no alert message appears

function validateForm()
{
isValid=true;
var x=document.forms[“dform”][“name”].value
if (x==null || x==“”)
{
alert(“Enter Name!”);
return isValid;
}
}
{
isValid=true;
var x=document.forms[“dform”][“selling_1”].value
if (x==null || x==“”)
{
alert(“Enter Selling Name!”);
return isValid;
}
}

Do you know about indenting code? If you indent your code, you will see where the problem lies.

You can wrap your code in

 tags, so that the indents will remain. For example, this code:


[code]
var function foo {
foo = ‘bar’;
return foo + ‘baz’;
}
[/code]



will result in:


function foo () {
var foo = ‘bar’;
return foo + ‘baz’;
}