Jump to content

preg_match multiple form fields


perky416

Recommended Posts

Hi Guys,

 

Firstly im no good with regex, i tried to get my head round it however i found it really confusing. I had to get help with this code last night from other forum members.

 

Im using the following code to validate my form fields:

 

	if(!preg_match('/^\s*\d*\.?\d{1,2}\s*$/', $price1)) 
	{ 
		$error[] = "Your price is invalid!";
	}

 

I have 16 textboxes that i need to validate using the same preg_match, is it possible to validate them all using the above code without having to rewrite it 16 times?

 

I tried the following but it did not work:

 

	if(!preg_match('/^\s*\d*\.?\d{1,2}\s*$/', $price1, $price2, $price3)) 
	{ 
		$error[] = "Your price is invalid!";
	}

 

Iv also had a browse through google for using preg match with multiple form fields however i cant find info relating to my problem.

 

Please could somebody help me out?

 

Many thanks.

Link to comment
https://forums.phpfreaks.com/topic/230115-preg_match-multiple-form-fields/
Share on other sites

  $prices = array($price1,$price2,$price3,$price4);
  foreach ($prices as $k => $v) {
    if (preg_match(/^\s*\d*\.?\d{1,2}\s*$/,$v)) continue;
    $errors[] = 'price is invalid!';
    break;
  }

 

basically all I did was I took YOUR code, threw a loop around it, and presto :)

Or, put the regex in a variable:

 

$priceRegEx = '/^\s*\d*\.?\d{1,2}\s*$/';
if(!preg_match($priceRegEx, $price1)) 
{ 
$error[] = "Your price 1 is invalid!";
}

if(!preg_match($priceRegEx, $price2)) 
{ 
$error[] = "Your price 2 is invalid!";
}

 

Even better: change the form to post the prices as an array (i.e. <INPUT type="text" name="price[]"> ... Then use RussellReal's code with a slight change:

  foreach ($_POST['price'] as $k => $v) {
    if (preg_match('/^\s*\d*\.?\d{1,2}\s*$/',$v)) continue;
    $errors[] = 'price is invalid!';
    break;
  }

 

Hi guys thanks for lending me a hand.

 

I decided to go with  the following as visually it looks the easiest for me to understand

 

$prices = array($price1,$price2,$price3,$price4);
foreach ($prices as $k => $v) {
if (preg_match('/^\s*\d*\.?\d{1,2}\s*$/,$v')) continue;
$error[] = 'price is invalid!';
break;
}

 

However when i press submit on the page the following error comes up:

Warning: preg_match() expects at least 2 parameters, 1 given in /home/user/public_html/websiteco.uk/rates.php on line 73

 

Do you have any ideas as to what is wrong?

 

Thanks again!!!

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.