Computer Programming web Web programming Tips



JavaScript Form Validation Example.

By Sergey Skudaev


I used different methods for form validation. This one I like the most. It takes all fields on the form and walk through.

To see source code, click on the webpage with right mouse button and select view source code.

I like this method, because it works even on fields created by cloning with javascipt. When you create an array of fields by clonning them with JavaScript, you cannot know index of the array for each field. It makes hard to write validate code by reference each field in the array. This method allows to validate all fields on the form. Just use name of the element to identify a field.

If a field is blank, its border turns red and its bsckground color turns yellow or orange. I do not use the "required" attribute on purpose for the better demonstration of the JavaScript function. In the real life, you should use the required attribute. Also, I do not validate the format of the entered data. You can find examples of that in Google.

In the first example of JavaScript validation function, I use style object. The whole code is in the text area below

JavaScript code for validation

The toDefault(x) function returns style properties back to default values.

Below in the text area is markup for the form.

 

HTML Form:

Some developers argue that using style object and changing its properties is not the best way to manipoulate DOM with JavaScript because it mixes behavior and presemtation.

It is said that structure, presentation and behavior should be pure. However, the-separation-of-structure-presentation-and-behavior-is-dead

Anyway, below I presented a different approach to changing the border and backgorund color while performing the form validation.

In the new validation function, I adding to the element that failed validation, a CSS class that changes the border and the background color. When visitor clicks inside the field, on the focus event, the class is removed and the border and the background color change back to default.

 

Form validation demo

 

 

My eBooks on Amazon.com

US    UK    BR    CA
US    UK    BR    CA
US   UK   BR   CA