cult3

Really simple inline Javascript validation

Aug 08, 2012

Table of contents:

  1. Creating your page
  2. Create the form
  3. Introducing the Javascript
  4. Javascript Regular Expressions
  5. Including a prompt
  6. Validation on form submission
  7. Extending our Javascript validation
  8. The full code

Just about any website or web application will require user input in one form or another. Whether it’s filling in a contact form or entering profile details into a new application, handling input errors can be the difference between a good or a bad user experience.

Have you ever filled in a huge form online, only to submit it and find that there was an error so you have to start again? Frustrating, isn’t it? It is these kind of fundamental errors that stop people returning to your website.

A much better way of solving this problem is to include inline validation that checks the user’s input as she progresses. This alerts the user to any errors and allows her to correct her errors before proceeding and losing her progress.

Inline validation powered by Javascript can be incredibly easy to implement, so there really is no excuse for not making your user’s lives as easy as possible.

Here is a tutorial for building your own Javascript validation that you can use on any input on your website or web application. I’ve intentionally kept it as easy, simple and lightweight as possible.

Creating your page

For this tutorial I’m just going to include all of the HTML and Javascript in one file to keep things simple.

So to start off, create yourself a little HTML file, like this.

<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8" />
  <title>Validation tutorial</title>
  <script>
    // JS
  </script>
</html>

Create the form

Next we need to a create an input field to validate. Create a form and an input field to allow you to enter your name.

<form action="">
  <fieldset>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" />
  </fieldset>
</form>

Next we need to add the onblur Javascript event to the input field. The onblur event allows you to run Javascript code when the user clicks away from the field. In this case, we want to be able to validate what the user has entered into the field, but we only want to do that when she has finished typing and has moved on.

Update your input field so it looks like this.

<input type="text" name="name" id="name" onblur="validateName(name)" />

As you can see, I’ve already named the Javascript function that we are going to make in a minute and I’ve passed in the name of the the field, in this case “name”.

Introducing the Javascript

Next we need to create the Javascript function.

In between the <script></script> tags at the top of the page, type the following code.

function validateName(x) {
  alert(document.getElementById(x).value);
}

Now save your file and open it in the browser. Enter some text into the input field and click away from the field. An alert box should appear with the text you entered.

So as you can see…

  • We created an input field
  • Added an onblur event which is triggered when the user clicks away
  • We then used a Javascript function to display the contents of the input in an alert box.

So hopefully you can see how the Javascript is run when it is triggered, and how we are able to get whatever the user has typed into the input box and do something with it.

Next I’ll show you how to validate the input.

Delete the following line from your Javascript.

alert(document.getElementById(x).value);

Javascript Regular Expressions

In order to validate the input, we have to test it against a set of rules that define a pass or fail. For example, you don’t want your users to enter & or @ or % into your name field because these characters don’t belong there.

In order to create a set of rules we use a Regular Expression (Regex). A Regular Expression is a way of matching an input to a set of rules. If the input matches the pattern it will return true, but if it does not, it will return false. So in the above example, if the input contained an @ when the pattern does not include an @ the test would return false and the validation would fail.

To create a validation for your name field, type the following line into your validateName() function.

var re = /[A-Za-z -']$/;

In the above line of code, we create a variable called re and assign it the regex of any capital letter (A-Z), any lower case letter (a-z), a space, a hyphen or an apostrophe.

With this regex rule saved, we can then run a test on our input to see if what was entered matches our defined rule.

Type the following code after the previous line.

if (re.test(document.getElementById(x).value)) {
    document.getElementById(x).style.background ='#ccffcc';
    return true;
} else {
    document.getElementById(x).style.background ='#e35152′;
    return false;
}

Here’s how the above code breaks down.

if (re.test(document.getElementById(x).value)) {

We test to see if the input value matches our rule.

If it does, we change the input box’s background to green.

document.getElementById(x).style.background = "#ccffcc";
return true;

But if it doesn’t, we turn the input box red.

} else {
    document.getElementById(x).style.background ='#e35152′;
    return false;
}

Save this out and refresh the page in your browser. You should now have a swanky input box that validates and gives a visual feedback to the user to tell them if their input was accepted or not.

Including a prompt

We’ve added a huge amount of usability to our form already, but there is still more we can do.

Not every input field will have obvious rules. For example, you might have a username field where you have a very precise set of allowed characters. In this instance, it is important to give your user some kind of message to help them complete the form. Without this prompt, you are likely going to annoy your user if they are repeatedly failing your validation test.

To add a validation prompt, add the following line of code to your form, just under your input field.

<span id="nameError" style="display: none"
  >You can only use alphabetic characters, hyphens and apostrophes</span
>

Next add the following line to the else branch of your if else statement in your Javascript.

document.getElementById(x + "Error").style.display = "block";

Save your file and fresh your browser. You should now be given a prompt when you enter invalid characters.

Finally add the following line to the if branch of your if else statement.

document.getElementById(x + "Error").style.display = "none";

This will clean up the prompt message once the user corrects their mistake.

Validation on form submission

The validation you’ve added so far is great because it allows the user to correct their mistakes as they progress. The next step is to prevent the form from being submitted if any of the validation rules are broken.

This is handy because we don’t really want to allow our user to submit a form with invalid data. Once the form is validated on the server side, it should spit it back out with an error message. However, we can stop it from ever getting this far by validating on the client side too.

Client side validation

So the first thing we need to do is to create a button to allow our form to be submitted.

<input type="submit" id="submit" name="submit" value="Submit" />

Next we need to add an onsubmit event. This is very similar to the onblur event we created earlier, the only difference is it is run only when the form is submitted.

Update your form tag so it looks like this.

<form action="" onsubmit="return validateForm()"></form>

More Javascript

Now we need to create the validateForm() function that will check the entire form for valid date.

In between the script tags, write the following.

function validateForm() {}

Next we need to create an error count.

// Set error catcher
var error = 0;

Next we run our validateName() function.

// Check name
if (!validateName("name")) {
  document.getElementById("nameError").style.display = "block";
  error++;
}

This runs the validateName() function on the name input field. If it returns false we know that the input field did not validate and so we display our error prompt and increase the error counter by 1.

Finally we create a little catch so if there are errors the form will not submit.

// Don't submit form if there are errors
if (error > 0) {
  return false;
}

Now when you save out your form you shouldn’t be able to submit it if there are errors. To successfully submit the form you need to correct all the errors so the fields turn green.

Extending our Javascript validation

You know have a full working example of inline validation and client side validation that you can implement on your website’s forms.

Hopefully this has given you enough of a start to extend the code to meet your requirements.

Here are some further Javascript validation functions that you can add to you code to extend it further and help you get started making some really awesome inline validation.

Validate email addresses

HTML:

<fieldset>
  <label for="email">Email</label>
  <input type="text" name="email" id="email" onblur="validateEmail(value)" />
  <span id="emailError" style="display: none"
    >You must enter a valid email address</span
  >
</fieldset>

Javascript:

// Validate email
function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (re.test(email)) {
        document.getElementById('email').style.background ='#ccffcc';
        document.getElementById('emailError').style.display = "none";
        return true;
    } else {
        document.getElementById('email').style.background ='#e35152′;
        return false;
    }
}

Validate dropdown boxes

HTML:

<fieldset>
  <label for="animal">Favourite Animal</label>
  <select name="animal" id="animal" onblur="validateSelect(name)">
    <option value="">Animals</option>
    <option value="cat">Cat</option>
    <option value="dog">Dog</option>
    <option value="badger">Badger</option>
  </select>
  <span class="validateError" id="animalError" style="display: none"
    >You must select your favourite animal</span
  >
</fieldset>

Javascript:

// Validate Select boxes
function validateSelect(x) {
    if (document.getElementById(x).selectedIndex !== 0) {
        document.getElementById(x).style.background ='#ccffcc';
        document.getElementById(x + 'Error').style.display = "none";
        return true;
    } else {
        document.getElementById(x).style.background ='#e35152′;
        return false;
    }
}

Validate Radio buttons

HTML:

<fieldset>
  <label for="hand">Left or Right handed?</label>
  <ul>
    <li>
      <input
        type="radio"
        name="hand"
        id="left"
        value="Left"
        onblur="validateRadio(id)"
      />
      <label for="left">Left handed</label>
    </li>
    <li>
      <input
        type="radio"
        name="hand"
        id="right"
        value="Right"
        onblur="validateRadio(id)"
      />
      <label for="right">Right handed</label>
    </li>
  </ul>
  <span class="validateError" id="handError" style="display: none"
    >Which hand do you use?</span
  >
</fieldset>

Javascript:

function validateRadio(x) {
  if (document.getElementById(x).checked) {
    return true;
  } else {
    return false;
  }
}

Validate Checkboxes

<fieldset>
  <label for="terms">Terms and Conditions</label>
  <ul>
    <li>
      <input
        type="checkbox"
        name="terms"
        id="accept"
        value="accept"
        onblur="validateCheckbox(id)"
      />
      <label for="accept"
        >Accept our <a href="#">Terms and Conditions</a></label
      >
    </li>
  </ul>
  <span class="validateError" id="termsError" style="display: none"
    >You need to accept our terms and conditions</span
  >
</fieldset>

Javascript:

function validateCheckbox(x) {
  if (document.getElementById(x).checked) {
    return true;
  }
  return false;
}

Validate your entire form

And finally, add the following code to your validateForm() function to validate your whole form when it is submitted.

// Validate email
if (!validateEmail(document.getElementById("email").value)) {
  document.getElementById("emailError").style.display = "block";
  error++;
}
// Validate Radio
if (validateRadio("left")) {
} else if (validateRadio("right")) {
} else {
  document.getElementById("handError").style.display = "block";
  error++;
}
// Validate Checkbox
if (!validateCheckbox("accept")) {
  document.getElementById("termsError").style.display = "block";
  error++;
}

The full code

Here is the full code.

<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8" />
  <title>Validation tutorial</title>
  <script>
    function validateName(x) {
    // Validation rule
    var re = /[A-Za-z -']$/;
    // Check input
    if (re.test(document.getElementById(x).value)) {
    // Style green
    document.getElementById(x).style.background ='#ccffcc';
    // Hide error prompt
    document.getElementById(x + 'Error').style.display = "none";
    return true;
    }else{
    // Style red
    document.getElementById(x).style.background ='#e35152′;
    // Show error prompt
    document.getElementById(x + 'Error').style.display = "block";
    return false;
    }
    }
    // Validate email
    function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (re.test(email)) {
    document.getElementById('email').style.background ='#ccffcc';
    document.getElementById('emailError').style.display = "none";
    return true;
    }else{
    document.getElementById('email').style.background ='#e35152′;
    return false;
    }
    }
    // Validate Select boxes
    function validateSelect(x) {
    if (document.getElementById(x).selectedIndex !== 0) {
    document.getElementById(x).style.background ='#ccffcc';
    document.getElementById(x + 'Error').style.display = "none";
    return true;
    }else{
    document.getElementById(x).style.background ='#e35152′;
    return false;
    }
    }
    function validateRadio(x) {
    if (document.getElementById(x).checked) {
    return true;
    }else{
    return false;
    }
    }
    function validateCheckbox(x) {
    if (document.getElementById(x).checked) {
    return true;
    }
    return false;
    }
    function validateForm() {
    // Set error catcher
    var error = 0;
    // Check name
    if (!validateName('name')) {
    document.getElementById('nameError').style.display = "block";
    error++;
    }
    // Validate email
    if (!validateEmail(document.getElementById('email').value)) {
    document.getElementById('emailError').style.display = "block";
    error++;
    }
    // Validate animal dropdown box
    if (!validateSelect('animal')) {
    document.getElementById('animalError').style.display = "block";
    error++;
    }
    // Validate Radio
    if (validateRadio('left')) {

    }else if (validateRadio('right')) {

    }else{
    document.getElementById('handError').style.display = "block";
    error++;
    }
    if (!validateCheckbox('accept')) {
    document.getElementById('termsError').style.display = "block";
    error++;
    }
    // Don't submit form if there are errors
    if (error > 0) {
    return false;
    }
    }
  </script>

  <form action="" onsubmit="return validateForm()">
    <fieldset>
      <label for="name">Name</label>
      <input type="text" name="name" id="name" onblur="validateName(name)" />
      <span id="nameError" style="display: none"
        >You can only use alphabetic characters, hyphens and apostrophes</span
      >
    </fieldset>
    <fieldset>
      <label for="email">Email</label>
      <input
        type="text"
        name="email"
        id="email"
        onblur="validateEmail(value)"
      />
      <span id="emailError" style="display: none"
        >You must enter a valid email address</span
      >
    </fieldset>
    <fieldset>
      <label for="animal">Favourite Animal</label>
      <select name="animal" id="animal" onblur="validateSelect(name)">
        <option value="">Animals</option>
        <option value="cat">Cat</option>
        <option value="dog">Dog</option>
        <option value="badger">Badger</option>
      </select>
      <span class="validateError" id="animalError" style="display: none"
        >You must select your favourite animal</span
      >
    </fieldset>
    <fieldset>
      <label for="hand">Left or Right handed?</label>
      <ul>
        <li>
          <input
            type="radio"
            name="hand"
            id="left"
            value="Left"
            onblur="validateRadio(id)"
          />
          <label for="left">Left handed</label>
        </li>
        <li>
          <input
            type="radio"
            name="hand"
            id="right"
            value="Right"
            onblur="validateRadio(id)"
          />
          <label for="right">Right handed</label>
        </li>
      </ul>
      <span class="validateError" id="handError" style="display: none"
        >Which hand do you use?</span
      >
    </fieldset>
    <fieldset>
      <label for="terms">Terms and Conditions</label>
      <ul>
        <li>
          <input
            type="checkbox"
            name="terms"
            id="accept"
            value="accept"
            onblur="validateCheckbox(id)"
          />
          <label for="accept"
            >Accept our <a href="#">Terms and Conditions</a></label
          >
        </li>
      </ul>
      <span class="validateError" id="termsError" style="display: none"
        >You need to accept our terms and conditions</span
      >
    </fieldset>
    <fieldset>
      <input type="submit" id="submit" name="submit" value="Submit" />
    </fieldset>
  </form>
</html>
Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.