Validating html with external javascript file

Hello,

i am new into this , so please help me
i have to make a html page , and check if the forms aren’t blank.
so i started with Name , but that even doesnt work.

this is my html code :


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Creating Forms</title>
<script type ="text/javascript" src="javascript1.js"> </script>
<link rel="stylesheet" type="text/css" 
href="style.css" />
</head>
<body>
<form method="aanmelden" action="index.html" onsubmit="return validateFirstName()" method="post">
<div id="form" >
<h3>Aanmelding WIES Congres</h3>
<p class="legend">Deelnemer</p>
<fieldset class="input2" id="Deelnemer">
<label>Naam/label>
<input type="text" name="name" maxlength="25" size="25"> 
<label class="right">Bedrijf/label>
<input class="right" type="text" name="company" maxlength="25" size="25">    
<br/>
<label>Adres/label>
<input type="text" name="address" maxlength="25" size="25"> <br />
<label>Postcode/label>
<input type="text" name="postalcode" maxlength="6" size="6"> <br />
<label class="right">Plaats/label>
<input class="right" type="text" name="city" maxlength="25" size="25">
<label>Land</label>
<select name="country">
<option value="" selected="selected">Nederland</option>
<option value="">België</option>
<option value="">Luxemburg</option>
<option value="">Duitsland</option>
<option value="">Frankrijk</option>
</select><br /><br />
<label class="labelwies">Wies lid/label>
<input type="radio" name="member" value="yes">Ja
<input type="radio" name="member" value="no" checked="checked">Nee<br />
<label class="labelwies">Nummer/label>
<input type="text" size="20" maxlength="10" placeholder="123"/><br />
<label class="labelwies">WIES Pin/label>
<input type="password" size="20" maxlength="4" />
</fieldset>
<p class="legend">Inschrijving</p>
<fieldset id="Inschrijving">
<div class="divleft">
<label>23 April/label><br /><br />
<input type="radio" name="day" value="entire" checked="checked">Hele dag<br />
<input type="radio" name="day" value="morning">Ochtend<br />
<input type="radio" name="day" value="midday">Middag<br /><br />
<input type="checkbox" name="lunch" value="lunch" />Inclusief Lunch <br/>
</div>
<div>
<label>22 April/label><br /><br />
<input type="radio" name="day2" value="entire" checked="checked">Hele dag<br />
<input type="radio" name="day2" value="morning">Ochtend<br />
<input type="radio" name="day2" value="midday">Middag<br /><br />
<input type="checkbox" name="lunch2" value="lunch2" />Inclusief Lunch <br />
</div>
</fieldset>
<p class="legend">Enquete</p>
<fieldset id="Enquete">
<label>Functie/label>
<input type ="radio" name="function" checked="checked" value="Manager"> Manager
<input type ="radio" name="function" value="Informatieanalist">Informatieanalist
<input type ="radio" name="function" value="Ontwikkelaar">Ontwikkelaar
<input type ="radio" name="function" value="Docent">Docent
<input type ="radio" name="function" value="Overig">Overig<br />
<label class="labelenquete">Vakgebied/label>
<select name="branche" multiple="multiple"> 
<option value="Automatisering">Automatisering</option>
<option value="Onderwijs">Onderwijs</option>
<option value="Overheid">Overheid</option>
<option value="Industrie">Industrie</option>
<option value="handel">Handel</option>
<option value="gezondheidszorg">Gezondheidszorg</option>
<option value="bank_en_verzekeringen">Bank en Verzekeringen</option>
<option value="Telecommunicatie">Telecommunicatie</option>
<option value="Overige">Overige</option>
</select><br/>
<label class="labelenquete">Bedrijfsgrootte/label>
<select name="personeel">
<option value="weining">0-10</option>
<option value="mkb">10-50</option>
<option value="mkbgroot">50-100</option>
<option value="zakelijk">100-500</option>
<option value="grootzakelijk">500 of meer</option>
</select>
</fieldset>
<p class="legend">Opmerkingen</p>
<fieldset id="opmerkingen">
<textarea name="company" cols="40" placeholder="Typ hier eventuele opmerkingen" rows="5"></textarea>    
</fieldset>
<p id="buttons">
<input type="submit" value="aanmelden" />
</p>
</form>
</div>
</body>
</html>

this is my js.

function validateFirstName() {
        var x = document.forms["aanmelden"]["name"].value;
        if (x == null || x == "") {
            alert("First name cannot be left blank.");
            return false;
        }
        else {
            return true;
        }
        }

whats wrong :frowning:

You have two method attributes on the form.

Do you mean form method and method?

form method=“aanmelden” action=“index.html” onsubmit=“return validateFirstName()” method=“post”

I fixed that , but it still does not work :frowning:

Hi,

Here’s an example of how you might do it:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Form</title>
  </head>
  
  <body>
    <form action="index.html" method="post" id ="aanmelden">
      <label>Naam</label>
      <input type="text" name="name" maxlength="25" size="25">
      <input type="submit" />
    </form>
    
    <script>
      function validateForm() {
        var name = form["name"].value;
        if (name === "") {
          alert("First name cannot be left blank.");
          return false;
        }
      }
      
       var form = document.getElementById("aanmelden");
       form.onsubmit = validateForm;
    </script>
  </body>
</html>

HTH

But the problem is that I have to use an external javascript file

No worries, just place the script in an external file.
It’ll work just as well.

<script type="text/javascript" src="path/to/the/file"></script>

I have this in my body now

<body> 
<form action="index.html" method="post" id ="aanmelden">
 <script type="text/javascript" src="j1.js"></script>
<div id="form" >
<h3>Aanmelding WIES Congres</h3>
<p class="legend">Deelnemer</p>
<fieldset class="input2" id="Deelnemer">
<label>Naam:</label>

and this is my js file 

     function validateForm() {
        var name = form["name"].value;
        if (name === "") {
          alert("First name cannot be left blank.");
          return false;
        }
      }
      
       var form = document.getElementById("aanmelden");
       form.onsubmit = validateForm;

but it won’t work .

I tried it with the internal javascript , that works …

i forgot something , now it works ! thanks !
If i want to do the same for the other forms , I just have to do the same but other names right ?

Yes, that is correct.

If you find yourself validating lots of form fields though, you might want to consider making a generic function that does the work for you.

I don’t have to validate that much fields , but it is possible to make a field red colored if something is not filled in ?

Well , I have a problem …

this is my JS now:

function validateForm() {
var name = form["name"].value;
if (name === "") {
alert("First name cannot be left blank.");
return false;
}
}
var form = document.getElementById("aanmelden");
form.onsubmit = validateForm;

       
function validateForm() {
var name = form["adres"].value;
if (name === "") {
alert("address cannot be left blank.");
return false;
}
}
var form = document.getElementById("aanmelden");
form.onsubmit = validateForm;

function validateForm() {
var name = form["city"].value;
if (name === "") {
alert("plaats cannot be left blank.");
return false;
}
}
var form = document.getElementById("aanmelden");
form.onsubmit = validateForm;

but if i don’t fill 3 of them in , it only gives a java error for field…

You can toggle a special class on the inputs you want to style.

function validateForm() {
  var nameInput = form["name"].value;
  if (nameInput.value === "") {
    alert("First name cannot be left blank.");
    nameInput.className += " error";

    return false;
  }
  else {
    nameInput.className = nameInput.className.replace("error", "");
  }
}

And put the styles in your css


.error {
  background: red;
}

You have defined the function validateForm() three times.
You really want to roll all of your validation logic into one function.

e.g.

function validateForm() {
  var name = form["name"].value,
      addres = form["adres"].value,
      city = form["city"].value; 

  // Do validation checks here

}

var form = document.getElementById("aanmelden");
form.onsubmit = validateForm;

Also, when you post large(ish) amounts of code, please use code tags.
Here’s how.

Well , now i have something like this :
function validateForm() {
var name = form[“name”].value,
addres = form[“address”].value,
city = form[“city”].value;
if (name === “”) {
alert(“Field cannot be left blank.”);
return false;
}

}

var form = document.getElementById(“aanmelden”);
form.onsubmit = validateForm;

But if i fill for example the city and the name field in , and leave one of the 3 blank … i want to get an error saying that i haven’t filled that field in . that doesnt work yet

Just check the other field values and alert appropriate content.


function validateForm() {
  var name = form["name"].value,
  address = form["address"].value,
  city = form["city"].value;
  if (name === "") {
    alert("Name cannot be left blank.");
    return false;
  }
  if (address === "") {
    alert("Address cannot be left blank.");
    return false;
  }
  if (city === "") {
    alert("City cannot be left blank.");
    return false;
  }
}

Or you can put these in a loop to prevent repeating yourself


function validateForm() {
  var mandatory = ["name", "address", "city"];
  for (var i=0, ii=mandatory.length; i<ii; i++) {
    var field = mandatory[i];
    var value = form[field].value;
    if (value === "") {
      alert(field + " cannot be left blank.");
      return false;
    }
  }
}

Well, in it’s simplest form, something like this should work:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Form</title>
  </head>
  
  <body>
    <form action="index.html" method="post" id ="aanmelden">
    	<div>
        <label>Name</label>
        <input type="text" name="name" maxlength="25" size="25">
      </div>
      
      <div>
        <label>Address</label>
        <input type="text" name="address" maxlength="25" size="25">
      </div>
      
      <div>
        <label>City</label>
        <input type="text" name="city" maxlength="25" size="25">
      </div>
      
      <input type="submit" />
    </form>
    
    <script>
      function validateForm() {
        var name = form["name"].value,
           address = form["address"].value,
           city = form["city"].value; 
						
        if (name === "") {
          alert("Name cannot be left blank.");
          return false;
        }
				
        if (city === "") {
          alert("City cannot be left blank.");
          return false;
        }
				
        if (address === "") {
          alert("Address cannot be left blank.");
          return false;
        }
      }
      
      var form = document.getElementById("aanmelden");
      form.onsubmit = validateForm;
    </script>
  </body>
</html>

However, it would be better to make the process more generic, as well as shy away from using alert() to display error messages:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Form</title>
    <style>
      form{padding: 15px}
      label{display: inline-block; text-align: right; width:60px; padding-right:5px;}
      input[type=submit]{margin-top: 20px;}
      .error{color: red; margin-left: 10px;}
    </style>
  </head>
  
  <body>
    <form action="" method="post" id ="aanmelden">
      <div>
        <label>Name:</label>
        <input type="text" name="name" placeholder="Name">
      </div>
      
      <div>
        <label>Address:</label>
        <input type="text" name="address" placeholder="Address">
      </div>
      
      <div>
        <label>City:</label>
        <input type="text" name="city" placeholder="City">
      </div>
      
      <input type="submit" />
    </form>
    
    <script>
      function removeElementsByClass(className){
        elements = document.getElementsByClassName(className);
        while(elements.length > 0){
          elements[0].parentNode.removeChild(elements[0]);
        }
      }    
    
      function flagError(field, prependText){
        var message = prependText + " cannot be left blank";
        form[field].insertAdjacentHTML('afterend', '<span class="error">' + message + '</span>');
      }
    
      function checkEmpty(field, prependText){
        if (form[field].value === ""){
          flagError(field, prependText);        
          isValidSubmission = false;
        }
      }
    
      function validateForm() {
        removeElementsByClass("error");
        
        checkEmpty("name", "First name");
        checkEmpty("city", "City");
        checkEmpty("address", "Address");
        
        return isValidSubmission;
      }
      
      var form = document.getElementById("aanmelden"),
          isValidSubmission = true;
          
      form.onsubmit = validateForm;
    </script>
  </body>
</html>

Here’s a demo.

HTH.

Edit:

Oops, beaten to it :slight_smile:

Thanks that worked!

Now I want the forms to be red if emtpy

i tried something like this :

function validateForm() {
var name = form[“name”].value,
address = form[“address”].value,
city = form[“city”].value;
if (name === “”) {
document.getElementById(‘name’).style.border = “solid 1px red”;
alert(“Vul uw naam in.”);

      return false;

without results …

No probs.

Try this:

form["name"].style.border = "solid 1px red";