【发布时间】:2012-03-13 13:28:07
【问题描述】:
我正在使用以下代码来验证输入字段的“集合”。每组 4 个字段(宽度/高度/长度/重量)。 如果我的一组输入字段为空,那么它不会在我的最终 $all 变量中显示该行数据。
这是有关该主题的先前主题:Removing Data from Variable if Input Fields incomplete - PHP - 效果很好。
然而,这次我使用的是“占位符”文本(输入字段 value 属性),因此我需要我的 PHP 来检查该占位符值是否存在。
这是我的伪代码,但我不确定如何使用常规 PHP 实现:
if ((pNUM-VALUEheight = "Height (cm)" OR pNUM-VALUEwidth = "Width (cm)" OR pNUM-VALUElength = "Length (cm)" OR pNUM-VALUEweight = "Weight (kg)"))
Then
// Don't store in $all variable
Else
// Do store set of values in $all variable
End If
这是我当前的 PHP 代码:
...
$ierrors = array();
$all = '';
// Loop over the values 1 through 20
foreach( range( 1, 20) as $i)
{
// Create an array that stores all of the values for the current number
$values = array(
'p' . $i . 'height' => $_POST['p' . $i . 'height'],
'p' . $i . 'width' => $_POST['p' . $i . 'width'],
'p' . $i . 'length' => $_POST['p' . $i . 'length'],
'p' . $i . 'weight' => $_POST['p' . $i . 'weight']
);
// Assume all values are empty.
$allEmpty = true;
// Validate every value
foreach( $values as $key => $value)
{
if( empty($value))
$ierrors[] = "Value $key is not set";
else
$allEmpty = false;
// You can add more validation in here, such as:
if( !is_numeric( $value) )
$ierrors[] = "Value $key contains an invalid value '$value'";
}
// Join all of the values together to produce the desired output
if (!$allEmpty)
$all .= implode( '|', $values) . "\n\n";
}
...
非常感谢这里的任何指示,或者如果需要任何澄清,请告诉我。
谢谢
【问题讨论】:
-
>> jsfiddle.net/bj8Ua/1 虽然这个例子在 JSFiddle 中不起作用,但这是我当前 HTML 和 JS 代码的 sn-p。谢谢。
标签: php forms validation foreach