Validation of a form with Javascript

Article that quickly summarizes the technique to validate a form on the client side with Javascript. It checks if its fields are correct and if so, the form is sent.

We are going to carry out a couple of complete examples of form validation. The validations are done in the browser itself, with Javascript code, before sending it. If there was any field not filled out or with wrong information, the form shows the field that is incorrect and asks the user to change it. If all the data in the form is correct, the form is sent.

We wanted to make a simple form, so that the exercise does not become too complicated. However, validations are performed on fields with different values, to make it more varied.

Alternatives to validate forms with Javascript

The exercise of validating a form is one of the most typical of Javascript and can be done in various ways, with different code alternatives, which can work perfectly in all cases.

Basically the process is always the same: access form field by field and check that the values ​​entered have the form we are expecting. If all the form fields are correct, then the submission is made to the server where the form has to be processed. The difference in approaches that we can find in practice and that we have brought you to this article varies mainly in how we access the form fields and send them.

Today we are going to show a couple of form validation alternatives, where you can see these different ways of working for validation with Javascript. They are slightly different styles of accessing the DOM, as coding customs, as well as the Javascript standard, have changed over time. We will start with a more current code, which we like better and which is technically a little more complex with greater versatility. Then we’ll look at a slightly older alternative that was used in much older versions of Javascript. Both work exactly the same in practice and are currently capable of running without issue in any browser.

Validation capturing the submit event of the form

In this first example we are going to capture the submit event of the form with Javascript, since the moment to send it is the right one to validate the data. We will carry out the validation and then, if everything went well, we will send it.

See also  Gimp and Photoshop

HTML code of the form

Before we get into the Javascript part, let’s take a look at the form we have:

User:

Key:

I want to draw attention to several things:

  • There is nothing special about the HTML form that would make it different from any other form where there is no validation (it has a normal submit button and there is no Javascript code anywhere and no events declared in handlers in the HTML). This fact, which may only seem anecdotal, is important, because the form as it is will work perfectly even if the browser has Javascript disabled, which improves accessibility. This is the fundamental difference with the second Javascript form validation example that we are going to see later.
  • The form has an “id” field, in the FORM tag, which will help us to access it through Javascript.
  • All the fields that we need to validate also have their “id”.

Javascript for form validation

Before going on to see the code, I want to summarize the steps that we are going to carry out for this validation.

  1. We will define a “submit” event to capture the moment the user will submit the form.
  2. Once the submit event of the form is captured with Javascript, we are going to block the submission, preventing it from sending with incorrect data.
  3. We will validate all the fields of the form.
  4. If all the fields are validated correctly, then we will send it ourselves using Javascript.

Once we understand the steps we have to carry out, we can move on to see the code. It consists of two parts, one for the definition of the Javascript events necessary to hook our majejadores to process the submission of the form and another part in which we perform the validation itself.

document.addEventListener(“DOMContentLoaded”, function() { document.getElementById(“form”).addEventListener(‘submit’, validateForm); }); function validateForm(event) { event.preventDefault(); var user = document.getElementById(‘user’).value; if(user.length == 0) { alert(‘You haven’t written anything to the user’); return; } var key = document.getElementById(‘key’).value; if (key.length < 6) { alert('The key is invalid'); return; } this.submit(); }

We start by defining a handler for the “DOMContentLoaded” event. This handler ensures that the rest of the code to be executed is done when the browser is actually ready to execute it.

Then we make a handler for the “submit” event of the form. As handler for this second event we indicate the function “validateForm()”. It is interesting here the access to the DOM of the page elements, which we are doing with “document.getElementById()” and sending its identifier (“id” attribute) as a parameter. This is another of the details that distinguishes this code from the simpler one that we will see later in this article.

See also  Sending 404 page not found error and then redirecting with header location doesn't work

The function validateForm() receives the event object as a parameter. This is something that happens with all Javascript event handlers. This “event” object is used to do various things, such as stopping the default behavior of an event. As it is the submit event, the default behavior is precisely the submission of the form, which we have stopped with the “event.preventDefault()” instruction.

Next we are accessing each element of the form, to study if they are correct or not. In the case that they are not, we display a message in an alert box and then exit the function with “return”. This return allows, once an error has been detected, to stop executing the function code.

Finally, if it didn’t exit because of any of the bad validations, then we submit the form. We do this with the submit() method of the form. Since we are inside an event handler defined by the form, the “this” variable corresponds to the form itself. Therefore, we can do the submission with a simple “this.submit()”.

That is all. I hope you have been able to understand the bases on this alternative for the validation of the form. Now we are going to present you a different, more basic one that you may also like and with which you can continue learning.

Second validation example

Now we are going to look at a slightly simpler validation example, with a slightly older coding style that we currently dislike, but that can help you if you are learning, to realize that we can do things in quite different ways and get the same result.

This example checks a field where a text must appear, another where a number greater than 18 must be entered and a last one with a select field where a value must have been selected.

Remember that in Javascript there are several ways to validate forms. In this example they have wanted to make things easy for people who are starting out.

The form code

When building a form that you want to validate, it is done with an HTML the same as a form that would be sent without validation. In our example we will use the DOM to access the fields from the object hierarchy, from the document and from the form object. In other examples on the Internet you will see that identifiers (“id” attributes) are used to access the fields. The result is actually the same.

See also  supersampling

The form with which we are going to work is the following:

< /tr>

Name: < /td>
Age:
Interest:

It is any form. The only points where we should pay attention are:

  • The name of the form, “fvalida”, which we will use to refer to it through Javascript.
  • The submit button, which instead of being a regular submit, is a button that calls a function, which is responsible for validating the form and submitting it if everything was correct.

Javascript function to validate the form

Now we will see the function that we have created to validate the form. Valid_send() is called. Simply, for each form field, it checks that the entered value is correct. If it is not correct, it displays an alert message, sets the focus of the application on the field that has given the error and exits the function, returning the value 0.

If all the fields were correct, the function continues until the end, without exiting, since there are no incorrect fields. Then it executes the last statement, which is the submission of the form.

Let’s see the entire function, although later we will explain it in parts.

function validate_send(){ //validate the name if (document.fvalid.name.value.length==0){ alert(“You have to write your name”) document.fvalid.name.focus() return 0; } // validate the age. must be an integer greater than 18 age = document.fvalid.age.value age = validateInteger(age) document.fvalid.age.value=age if (age==””){ alert(“You must enter an integer in your age.”) document.fvalid.age.focus() return 0; }else{ if (age<18){ alert("You must be over 18 years old.") document.fvalid.age.focus() return 0; } } //I validate the interest if (document.fvalid.interest.selectedIndex==0){ alert("You must select a reason for your contact.") document.fvalid.interest.focus() return 0; } //the form is submitted alert("Thank you very much for submitting the form"); document.fvalida.submit(); }

In the first block, the name field is validated. The validation that is done is…

Loading Facebook Comments ...
Loading Disqus Comments ...