2009-12-05 4 views
0

변수에 값을 입력하고 배열에 변수 값을 넣은 다음 양식을 유효하게하려고 시도하고 있습니다. 유효하지 않은 필드에 대해 오류 메시지를 출력합니다. 채워 넣습니다. 두 가지 문제가 있습니다. 첫째, if 문은 필드가 비어 있거나 == 'undefined'인 경우에도 모든 값에 대해 실행되고 두 번째로 변수 값 대신 변수의 실제 이름을 출력하는 방법을 알지 못합니다. 배열을 사용하여 PHP 폼 유효성 검사 - 변수 이름 인쇄

print_x($variable)//prints 'variable' instead of 'hello'

$variable = 'hello'; 

예를 들어 I는 다음과 같이 두 가지 방법을 시도했다.

$error_message = "The following fields must be filled in:<br />"; 
     $fields_to_validate_arr = array($category,$producer,$product_name,$image_name,$description,$stock_quantity,$min_sale); 
     foreach($fields_to_validate_arr as $v){ 
      if(empty($v) || $v = 'undefined'){//using variable bariables 
       //increment the error message with a custom error message. 
       $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";//no need to use variable variables 
      } 
     } 

그리고 내가 변수 변수

$error_message = "The following fields must be filled in:<br />"; 
    $fields_to_validate_arr = array('category','producer','product_name','image_name','description','stock_quantity','min_sale'); 
    foreach($fields_to_validate_arr as $v){ 
     if(empty($$v) || $$v = 'undefined'){//using variable bariables 
      //increment the error message with a custom error message. 
      $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";//no need to use variable variables 
     } 
    } 

변수가

$category = myescape_function($_POST['category']); 

감사

지금까지 첫 번째로

답변

1

자신의 입력 변수 배열을 생성 할 필요가 없습니다 $ _POST :

값이 별도의 변수에 저장되지 않기 때문에
$_POST = array_map('myescape_function', $_POST); 
foreach($fields_to_validate_arr as $v){ 
    if(empty($_POST[$v]) || $_POST[$v] == 'undefined'){ 
     //increment the error message with a custom error message. 
     $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />"; 
    } 
} 

, 변수의 이름을 인쇄 문제 가치가 사라지는 것보다 오히려. 당신은 정말 멋진 얻고 싶은 경우에

, 사용자 지정 유효성 검사기에 대한 지원을 추가 할 수 있습니다

function inputExists($name, &$source) { 
    return !empty($source[$name]) && 'undefined' != $source[$name]; 
} 
function inputIsNumeric($name, &$source) { 
    return inputExists($name, $source) && is_numeric($source[$name]); 
} 
// checks for U.S. phone numbers only 
function inputIsPhone($name, &$source) { 
    if (inputExists($name, $source)) { 
     // strip whatever non-numeric 
     $value = preg_replace('/[-.,() \t]+/', '', $source[$name]); 
     return preg_match('^(1?[2-9]\d{2})?[2-9]\d{6}$', $value); 
    } 
    return False; 
} 
function inputMatchesRE($name, &$source, $RE) { 
    return inputExists($name, $source) && preg_match($RE, $source[$name]); 
} 
function nameAndValidator($name, $validator) { 
    if (function_exists($validator)) { 
     return array('name' => $name, 'validator' => $validator, 'data' => ''); 
    } elseif (is_numeric($name)) { 
     // if index is numeric, assume $validator actually holds the name 
     return array('name' => $validator, 'validator' => 'inputExists', 'data' => ''); 
    } else { 
     return array('name' => $name, 'validator' => 'inputMatchesRE', 'data' => $validator); 
    } 
} 

$fields_to_validate_arr = array('name', 'street' => '/^\d+ +[a-z ]+(ave|st|wy|way|ln|lp|blvd)$/i', 'age'=> 'inputIsNumeric', 'phone' => 'inputIsPhone'); 

$_POST = array_map('myescape_function', $_POST); 

foreach($fields_to_validate_arr as $name => $validator){ 
    list($name, $validator, $data) = nameAndValidator($name, $validator); 
    if(! call_user_func($validator, $name, $_POST, $data)){ 
     //increment the error message with a custom error message. 
     $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />"; 
    } 
} 
+0

개인적으로, 저는 is_numeric이 과학 표기법, 16 진수 등을 받아들이 기 때문에 ctype_digit 또는 is_numeric 대신에 사용합니다 (이것은 폼의 유효성을 검사 할 때 대부분의 사람들이 찾고있는 것이 아닙니다). – preinheimer

1

처럼 내 코드에서 추가로 최대 할당을 사용하는 다른 방법 코드 블록에 IF 문에 버그가 있습니다. $ v = '정의되지 않음'은 매번 true로 평가됩니다. IF 문에 항등 연산자를 사용해야합니다. 당신이 이미 가지고 있기 때문에

$error_message = "The following fields must be filled in:<br />"; 
    $fields_to_validate_arr = array($category,$producer,$product_name,$image_name,$description,$stock_quantity,$min_sale); 
    foreach($fields_to_validate_arr as $v){ 
     if(empty($v)){ //using variable variables 
      //increment the error message with a custom error message. 
      $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";//no need to use variable variables 
     } 
    } 
+0

내가 그들을 볼 수 없습니다, 그들은 무엇입니까? – andrew

+0

Oh im missing == – andrew

+0

@andrew - 설명문으로 편집 –