Jump to content

Input Validation


Omzy

Recommended Posts

This is probably a very easy one and I have searched online but there are so many different methods that it's confusing me.

 

Basically I have a form with an input field, the form is submitted via POST and all I want to do is validate the input so that special characters are not allowed - for example - brackets, commas, apostrophes, and all other special characters, apart from dash and underscore.

 

Is there a built-in PHP function that will do this?

 

Also are there any other techniques I can use to validate the input fields so that they are secure from SQL injection attacks and bogus content?

Link to comment
https://forums.phpfreaks.com/topic/158561-input-validation/
Share on other sites

I would suggest for you to use javascript to check this.

 

Here is a javascript function

 

function Check_chars( data )
{
   var iChars = "!@#$%^&*()+=-[]\\\';,{}|\"<>?~_"; // Just put here what You want to be considered as invalid char
   for (var i = 0; i < data.length; i++) {
  	if (iChars.indexOf(data.charAt(i)) != -1) {
  	  //alert ("Your string has special characters. \nThese are not allowed.");
  	return false;
  	}
  }
  return true;
}

Link to comment
https://forums.phpfreaks.com/topic/158561-input-validation/#findComment-836286
Share on other sites

Regular expressions are very useful for filtering out a custom set of characters. I'd recommend reading the tutorials for in the future.

 

To filer out all characters except a-z A-Z 0-9 _ -:

 

$str = "(-test'String001_),";

$str = preg_replace('/[^\w-]/', '', $str);

print $str;

Link to comment
https://forums.phpfreaks.com/topic/158561-input-validation/#findComment-836288
Share on other sites

OK well I tried:

 

if(preg_match('/[^w-]/', '', $str))
{
echo "Error";
}

 

But that doesn't seem to work. It also seems to be causing an "array to string conversion" error further down the script.

 

Looks like you're calling preg_match wrong, as the second argument is supposed to be the string you're checking.  So, try:

if(preg_match('/[^w-]', $str))
{
   echo "Error";
}

Link to comment
https://forums.phpfreaks.com/topic/158561-input-validation/#findComment-836347
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.