Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.