Validating all text fields.





0/5 (0 vote)
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.
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() { //Checking all text boxes 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; } } } // Checking all text areas. 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; } } // This function checks the text field for script input. function checkScriptInput(obj) { var legalChars = /[\<\>]/; if (legalChars.test(obj.value)) { obj.style.background = ‘#FFF1F5′; return false; } else { return true; } } /// Function for displaying error message. function ShowInvalidInputDiv() { // Here you should write the code for displaying some error message to the user. }