伙计们,我如何验证 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);
}
}
?>