Monday, 13 February 2012

Data validation with Javascript


Validating a web form with Javascript

Aim:
The aim of this practical is to ensure that the data that is entered is valid with respect to the formatting and the types of characters that are present within it. For example, A name should not have numbers, an email is supposed to have the @ sign and the @ sign is supposed to before the last dot.

Objective:
Our objectives are to create an HTML form with input boxes that receive user inputs and calling the respective functions that checks the validity of the values of the inputs boxes before submitting it the data to the server. All errors were to be displayed in the innerHTML attribute of the span element of the HTML page.

Implementation:
With this page, I used a table to hold all my objects on screen. I gave all the objects I would be referring to in the script “ids” so that I could get access them. To get an object in the HTML page with script to use, the getElementById(“objectID”) method of the document class is used. From one of the examples we did in class, I realized I could use the form id in the script directly without having to get the form object (document.getElementById(“formId”)) in the script like using the form Id to call methods of the form object and even get access to the other elements of the form. For example take a form with id = myForm. In the script, one can just say myForm.elements(“myTextBoxId”). When I used this format to get my input boxes object in the form, it seemed to work however after sometime, I realised the browser did not respond to the event triggers and no error registered in the debugger’s console. After speaking to some of my friends who explicitly got the form object before using it, I realised later the code format I used (ie using the form id directly) might not be supported by all browsers.
With the validation of data, we used mechanisms like comparing the string the user entered with a regular-expression object. This mechanism also came with its own problems. First of all, one had to know the format of the regular expression parameter to correctly specify the behaviour/characteristic of the regular expression object. For example [A-z] or [A-Z,a-z] is for characters from capital A through to small z. The regex can get complex once you want a quite a complex characteristic. For the regex I used ([A-z]), I intend it to be used only alphabets, however after doing the comparison, it was able reject only numbers but accepted the combination of numbers and alphabets.
  

No comments:

Post a Comment