Form Validation

Overview


Capturing the Button Click


The first thing that needs to happen is a way to capture whenever the user clicks the submission button. JQuery provides a simple method to do this. If the button has be given the id "submit", the following code will register the anonymous function to fire whenever the user clicks the submit button.


$("#submit").click(()=>{
  //do something
});
					

Form Input Values


Next, each input value needs to be inspected to determine whether it is valid. Some inputs (such as a drop down box), do not need to be validated.

In JQuery, it is easy to retrieve the value of a input. For example, the inputted value of an input element with id "input1" can be retrieved as follows:


 let value1 = $('#input1').val();
					


Similarly, within the button click handler, one could retrieve the values of all the inputs in the form.


$("#submit").click(()=>{
  let value1 = $('#input1').val();
  let value2 = $('#input2').val();
});
					

Validating Form Input Values


Once the values have been retrieved, the last step is check that each value is valid. Here, once must code the rules that are specific to the form at hand. In the following example, we check that the inputted value is not empty (equal to the empty string ""). If the input is empty, we add a message to the form element with id "input1-validation".


$("#submit").click(()=>{
  let valid = true;
  let value1 = $('#input1').val();
  if(value1.trim() === '') {
    valid = false;
    $('#input1-validation').html('input1 is empty');
  }
  //check other inputs
  if(valid === true){
	//submit the form to the database
  }

});
					

Contents