您应该在服务器端验证这一点。客户端验证是可选的。您可以声明字段的验证类型,并为您的表单构建通用验证器。如果您不知道我的意思,请尝试查看 AngularJs 声明式代码构建。它是构建表单的最佳方式,Angular 也是构建表单的良好且非常快速的框架。
http://angularjs.org/
http://docs.angularjs.org/#!/cookbook/advancedform
看看这行:
<input type="text" name="form.address.line1" size="33" ng:required/> <br/>
<input type="text" name="form.address.city" size="12" ng:required/>,
<input type="text" name="form.address.state" size="2" ng:required ng:validate="regexp:state"/>
<input type="text" name="form.address.zip" size="5" ng:required
validate="regexp:zip"/>
对于您的服务器端,您还可以定义一些结构,其中将包含表单字段、验证方法和每个字段的错误字符串。然后在循环中,根据您的信息结构验证每个字段。您可以轻松管理以这种方式构建的表单。
PHP 中的示例:
表格数据:
$formData = array (
array(
'ID' => "name",
'validate' => '/.+/',
'label' => 'Your name',
'errorMsg' => "This field is required",
'type' => 'text'
),
array(
'ID' => "Phone number",
'validate' => '/^[0-9+ ]+$/',
'label' => 'Numer telefonu',
'errorMsg' => "Please provide proper telephone number",
'type' => 'text'
)
);
验证器和表单生成器(对不起,这里的代码简单而混乱):
$s = '';
foreach ($formData as $input){
$s .= sprintf('<label for="%s">%s</label>',$input['ID'],$input['label']);
if (isset($_POST[$input['ID']]) && !empty($input['validate']) && !preg_match($input['validate'],$_POST[$input['ID']])){
$error = true;
$s .= sprintf('<div class="formErrorValidate">%s</div>',$input['errorMsg']);
}
if (isset($_POST[$input['ID']])) $htmlMsg = str_replace('%'.$input['ID'].'%',$_POST[$input['ID']],$htmlMsg);
if ($input['type'] == 'textarea'){
$s .= sprintf('<textarea name="%s" id="%s">%s</textarea>',$input['ID'],$input['ID'],(isset($_POST[$input['ID']])?$_POST[$input['ID']]:''));
} else {
$s .= sprintf('<input type="%s" name="%s" id="%s" value="%s"/>',$input['type'],$input['ID'],$input['ID'],(isset($_POST[$input['ID']])?$_POST[$input['ID']]:''));
}
}