Jump to content

Php input validation - exact input only


oddball25

Recommended Posts

Hey

 

I am struggling in trying to find a solution for the above problem. I have a simple html form and have some php code set up to validate the user input. Below is an example of how i am validating one particular field:

 

function validateField1($field1){
	//if it's NOT valid
	if(strlen($field1) < 1)
		return false;
	if(!preg_match('/^[A-Za-z0-9 ]+$/', $field1))
	return false;
	//if it's valid
	else
                return true;

 

So for that field if the user fails to enter anything or if they include anything other than Lower/Uppercase letters, numbers and a space then the script returns false and brings up the error.

 

Now i am trying to set up some fields where by the user must match their input with an exact string that i will set for it to correctly validate otherwise it will flag an error.

 

So for example on 'field 2' - the user must enter the input of 'red' or 'blue' or 'green' or 'pink'. Anything other than either 1 of these will not be passed.

 

Now i know instantly from that it would seem i should just use the 'select name' and 'option' values for my html to just have those 4 options in a drop down list to select but it needs to be a typed user input not selected from a list.

 

Am i able to add exact terms into the above validation example or do i need to use a different technique? I have a feeling that it might be best to use MySql with this in the form of a database but i unfortunately have no knowledge of this language at present...

 

Is anyone able to help me out on this one?

 

Many thanks

 

Jon

Link to comment
https://forums.phpfreaks.com/topic/191964-php-input-validation-exact-input-only/
Share on other sites

Sure, this would be ideal for an option or radio etc. but this still has it's uses:

 

What you do is put your exact strings into an array and use 'in_array()' to test the matches. Like so:

 


$myarr = array('red','green','orange');

if(in_array($_POST['yourfield'], $myarr)){
  return true;
}else{
return false;
}

 

Hope that helps.

An array is ideal for what i am doing thank you, simple really, shows that i am still a newbie with PHP! :D

 

Thank you again!

 

Yep, perfect and simple. I'm still a newbie! PHP is just so damn powerful you often overlook a lot of it's capabilities. I only knew how to do this because I'd done it before, not because I learned in_array. Difference is necessity vs study.. I always opt for necessity (with regards to php).

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.