Click here to Skip to main content
15,895,256 members
Articles / All Topics

Validating all text fields.

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
16 Sep 2010CPOL 4.8K  
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.

}
This article was originally posted at http://blog.taknikkar.com?p=9

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Syed Mujtaba Hassan
Software Engineer
Intelligentsia Software (Pvt) Ltd Islamabad Pakistan.

Comments and Discussions

 
-- There are no messages in this forum --