夥計們我如何驗證php中的操作數輸入?即時通訊創建一個非常簡單的計算器頁面..所以'+'' - '和'。'除了數字之外,也是有效的輸入。所以is_numeric是不夠的驗證。此外,如果你們知道在drupal中實現這種驗證的方式,請隨時發佈。即時通訊使用Drupal。順便說一下,這裏是我的drupal代碼。我創建了一個簡單的計算器模塊如何驗證有效輸入只適用於方程式中的操作數
<?php
/**
* Implements hook_menu()
*/
function calculator_menu(){
$items['calculator-page'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array('calculator_form'),
'access callback' => TRUE,
);
return $items;
}
function calculator_form(){
$form['firstoperand'] = array(
'#title' => t('First operand'),
'#type' => 'textfield',
'#required' => TRUE,
'#rules' => 'numeric'
);
$form['operator'] = array(
'#type' => 'select',
'#options' => array(
'+' => t('Plus'),
'-' => t('Minus'),
'*' => t('Times'),
'/' => t('Divided by'),
),
'#required' => TRUE,
);
$form['secondoperand'] = array(
'#title' => t('Second operand'),
'#type' => 'textfield',
'#required' => TRUE,
'#rules' => 'numeric'
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Generate',
);
$form['#submit'][] = 'calculator_form_submit';
return $form;
}
function calculator_form_submit($form, &$form_state){
$firstoperand=$form_state['values']['firstoperand'];
$operator=$form_state['values']['operator'];
$secondoperand=$form_state['values']['secondoperand'];
if(!is_numeric($firstoperand) || !is_numeric($secondoperand)){
drupal_set_message("Must use numbers");
}
else{
/*if($operator=='+'){
$result= $firstoperand+$secondoperand;
}
if($operator=='-'){
$result= $firstoperand-$secondoperand;
}
if($operator=='*'){
$result= $firstoperand*$secondoperand;
}
if($operator=='/'){
$result= $firstoperand/$secondoperand;
}*/
$result = $firstoperand+$operator+$secondoperand;
drupal_set_message($result);
}
}
?>
Belmark嗨利用正則表達式規則,我不知道任何Drupal,但PHP應該是相似的。你已經註釋掉的部分看起來不錯,但你需要在第一個'if'之後使用'else if'才能正確測試。你在哪裏發現錯誤? – Martin 2013-03-15 15:37:16
@Martin,這是先生的另一個問題。我曾研究過此前的問題。現在我想驗證輸入,以便它可以允許數字,'+',' - '和'。'只要。 – 2013-03-15 15:44:34