Developing a simple validation library in JavaScript
This series of articles mainly lists some of the most commonly used JavaScript functions for client side validation of HTML forms. You can reuse these scripts to inject into server side controls easily.
Within the above code, I mainly created a TEXTAREA (multi-line text box) and a button. The textbox is named “Textarea1” and the button is named “Button1”. The button is defined with an “onclick” event which calls a JavaScript function named “Button1_onclick”, which is defined as follows:
function Button1_onclick() { var v = document.all("Textarea1").value; alert(isContainSpacesOrTab(v)); }
The above function defines a variable “v”, which is assigned with a value available (or typed) in the textarea “Textarea1”. The same variable is passed as a parameter to another JavaScript function, “isContainSpacesOrTab” (which is defined as follows). The value returned by the function “isContainSpacesOrTab” is finally displayed in the form of a message box, using an “alert” statement. Now, let us look into the “isContainSpacesOrTab” function.
The above function simply accepts any value (as a parameter value) into the variable “val”. The first “if” statement in the function “isContainSpacesOrTab” simply checks for “null”. The second “if” statement in the same function counts the number of characters available. If no characters are found, it returns “true”.
If any characters are found, we go through each character (using a “for” loop) and check whether the character matches with a space or a tab character (\t). If any character is found to be a space or tab, we return true. Finally, if none of the “if” statements work, we return “false”.
Within the above function, we checked only spaces and tabs. If we needed to check for “carriage returns”, we would work with the character “\r”. Similarly, if we needed to check for new line, we would work with the character “\n”. You can test for these functionalities by modifying very few lines in the above code!