Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Validating all text fields.

, 16 Sep 2010
Rate this:
Please Sign up or sign in to 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. function ValidateAllFieldsForScripting() { //Checking

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.

}

License

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

Share

About the Author

Syed Mujtaba Hassan
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 --
| Advertise | Privacy | Mobile
Web02 | 2.8.140921.1 | Last Updated 16 Sep 2010
Article Copyright 2010 by Syed Mujtaba Hassan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid