Marilee
Marilee

Reputation: 1598

Javascript - Validation returning false when correct condition is met

Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:

  1. If error is found change text field background color to red, change field value to error message
  2. If no errors are found, proceed

My problem

The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?

Code follows:

function validate(){
    //form validation

    var name=document.getElementById("name");
    var surname=document.getElementById('surname');

    //name
    if (name.value=='') {
        name.style.backgroundColor="red";
        name.style.color="white";
        name.value="Name is required"
        return false;
    } 

    else if(isNaN(name)==true){
        name.style.backgroundColor="red";
        name.style.color="white";
        name.value="Name: Only enter letters A-Z"
        return false;
    } 

    //surname
    if (surname.value == ""){
        surname.style.backgroundColor="red";
        surname.style.color="white";
        surname.value="Surname is required"
        return false;
    }

    else if(isNaN(name)==true){
        surname.style.backgroundColor="red";
        surname.style.color="white";
        surname.value="Surname: Only enter letters A-Z"
        return false;
    } 
    return true;
 }

HTML

 <form id="enquire" method="post">
    <h2>Test Drive an Audi Today</h2>
    <input type="text" id="name" value="Name" class="textbox"  name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
    <br />
    <input type="text" id="surname" value="Surname" class="textbox"  name="surname"  onfocus="if(this.value=='Surname') this.value='';"  /><br />

    <input type="submit" name="submit" class="butt" value="Send" onclick="return validate()"  />

Upvotes: 0

Views: 167

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number

isNaN(name.value)

Demo: Fiddle

Upvotes: 4

Rashmin Javiya
Rashmin Javiya

Reputation: 5222

You should use onsubmit event of form instead of click.

<form id="enquire" method="post" onsubmit="return validate()">

Upvotes: 1

Related Questions