JavaScript Coder

Javascript validation simple example code

javascript form validation example validation javascript simple validation example

Here is a simple form validation code that validates a simple form No additional library is used. It is pure Javascript

First step - add an event listner for form submit event

Here is the code that does that step:

document.getElementById('myform').addEventListener('submit', validateForm);

function validateForm()
{

}

First, we get the form DOM object using the ID attribute of the form. Then we listen to the form submit event.

Next, we have to validate each of the fields in the form.

Here is the function that checks whether “FirstName” was entered:

function validateFirstName()
{
  var first_name =  document.getElementById('myform_firstname').value;
  if(!first_name || first_name.length < 2)
    {
       showError("myform_firstname", "Please enter your FirstName");
       return false;
    }
    return true;
}

This function just gets the value of the field and then throws error if the value is shorter than 2 characters. You can customize and add even more tighter checks.

The validation for LastName field is similar. In case of Phone number, we have some extra checks. This function checks the correct format for the phone number using regular expression:

function validatePhoneNumber() 
{
    var phone = document.getElementById('myform_phone').value;
    var re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
    if(!phone || !re.test(phone))
      {
        showError("myform_phone", "Please enter a valid phone number");
        return false;
      }
  return true;
}

You may be wondering what does the showError() do. There is no such built-in function. Let us now add a few utility functions.

function showError(element_id, message)
{
  var element = document.getElementById(element_id);
  var error_div = document.createElement('div');
  error_div.id = element_id+'_error';
  error_div.className='error';
  error_div.innerHTML = message;
  element.parentNode.insertBefore(error_div, element.nextSibling);
  
}
function removeElementsByClass(rootElement,className)
{
    var elements = rootElement.getElementsByClassName(className);
    while(elements.length > 0)
    {
        elements[0].parentNode.removeChild(elements[0]);
    }
}
function removeErrorMessages()
{
  removeElementsByClass(document.getElementById('myform'), 'error');
}

The showError() function appends an error message next to the element so that the error message is displayed just below the element.

removeErrorMessages() function clears all previous error messages from the form just before validating the form again.

Now that we are ready to complete the validateForm() function, let's finish that last bit:

function validateForm(event) 
{
    removeErrorMessages();
    if (validateFirstName() &&
        validateLastName() &&
        validatePhoneNumber()
    ) 
    {
        return true;
    } 
    else 
    {
        event.preventDefault();
        return false;
    }

}

Try the demo

See Also