前端对表单输入信息的格式进行验证有很多方法,下面两种方式效果比较不错也很简单。其中第一种仅在点击提交按钮后显示,而第二种很灵活。
对于使用Bootstrap开发的前端,感觉第二种风格比较统一。
第一种:利用html5的新特性
在<input>标签中加入新的属性
required:要求不能为空
patten=”正则表达式”:设置内容的格式
title=”提示信息”:弹出框的显示内容
这一种比较简单,没有利用Bootstrap的特性。效果如下:

第二种:配合bootstrap的样式表
有一些现成的验证插件,但自己写也比较简单。利用bootstrap中表单不同状态不同样式,以及对应的图标和帮助文字,主要工作就是判断信息格式,根据结果修改对应标签的class。
这里修改了<div>:form-group has-feedback has-success(has-error)
帮助文字以及图标的class。
一个简单例子如下:
html代码:
<div id="accountDiv"class="form-group has-feedback">
<label>用户名</label>
<input type="text" name="account" id="account" class="form-control" placeholder="请输入6-16位字符" onclick="check_info()"
required pattern="[a-z0-9A-Z]{6,16}" title="帐号应为6-16位的字母或数字">
<br><br><br>
账号为6-16位字符
</div>js代码:
var account = document.getElementById("account").value;
if ((account.length != 0) && ((account.length < 6) || (account.length >16)))
{
document.getElementById("account_warning").className = "help-block";
document.getElementById("accountDiv").className="form-group has-error has-feedback";
document.getElementById("accountIcon").className="glyphicon glyphicon-remove form-control-feedback";
}
else if(account.length != 0)
{
document.getElementById("account_warning").className = "help-block hide";
document.getElementById("accountDiv").className="form-group has-success has-feedback";
document.getElementById("accountIcon").className="glyphicon glyphicon-ok form-control-feedback";
all_info_are_right--;
}
else
{
document.getElementById("account_warning").className = "help-block hide";
document.getElementById("accountDiv").className="form-group has-feedback";
document.getElementById("accountIcon").className="hide";
}效果如下:
