This is the first part (and very first blog post which I had repeatedly procastinated over the years) of my javascript posts. Alright, i admit it, JavaScript is my friend! I enjoy exploiting the hell out of javascript to bring out it's practical usage in web forms' input validation.
One of the common ways and often repeated (copy-and-pasted?) validation techniques is to check if the user input is whether it is numeric or a valid character string. I've researched some code written in another language, modified it. Suppose I have an input type="text" in your form with an id of TextBox1:
I did it this way.
var TEXTBOX_forValidation = document.getElementById("TextBox1");
var stringValidNumericCharacters = "0123456789";
var allValidChars = true;
//..check for invalid input
for (i = 0; i < stringValidNumericCharacters .length &&
bool_allValidChars == true; i++) {
stringSingleCharacter = stringForValidation.charAt(i);
if (stringValidCharacters.indexOf(stringSingleCharacter) == -1)
bool_allValidChars = false;
}
if (!bool_allValidChars)
//..write error handler code here
I took it some few steps further. I also wanted to validate for invalid characters. I modified stringValidNumericCharacters to
var stringValidCharacters = "0123456789!@#$%&*( )\"\'-+=?.,/\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
Then i thought also of restricting certain words and phrases to possible malicious input from users:
Var errMessage = "";
var reserved_words = new Array("select", "select * from", "drop table", "insert into", "exec", "insert", "insert into", "update", "delete", "drop");
//..check for the existence of reserved words
for (var ctr = 0; i < reserved_words. length
&& bool_allValidChars == true; ctr++) {
if (stringForValidation.indexOf(reserved_words[ctr].toString())!=-1)
{
bool_allValidChars = false;
errMessage += "error: " + reserved_words[ctr];
}
}
if (!bool_allValidChars)
//..write error handler code here
If I need to restrict more phrases/words in the future I can add more entries into the arry definition of the client-side script.
That's it. My first blog post. Quick down and dirty but also practical. Attach is a .js file ready to be plugged into web forms.