I needed to validate all the text fields on the page and restrict the user from entering scripts into text fields and text areas. Following is the solution (Using a simple regular expression).
This function should be called on submit of the form.
function ValidateAllFieldsForScripting() {
var f = document.getElementsByTagName(‘input’);
var isInputValid = true;
for (var i = 0; i < f.length; i++) {
if (f[i].getAttribute(‘type’) == ‘text’) {
if (checkScriptInput(f[i]) == false) {
isInputValid = false;
}
}
}
f = document.getElementsByTagName(‘textarea’);
for (var i = 0; i < f.length; i++) {
if (checkScriptInput(f[i]) == false) {
isInputValid = false;
}
}
if (isInputValid)
return true;
else {
ShowInvalidInputDiv();
return false;
}
}
function checkScriptInput(obj) {
var legalChars = /[\<\>]/;
if (legalChars.test(obj.value)) {
obj.style.background = ‘#FFF1F5′;
return false;
} else {
return true;
}
}
function ShowInvalidInputDiv() {
}
This article was originally posted at
http://blog.taknikkar.com?p=9