此表单验证插件会对表单字段进行验证,实时提示用户输入信息,用户体验非常好,验证提示紧随input框!
以下为表单验证案例代码:
<script type="text/javascript" src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script> //引入的插件
<script type="text/javascript">
$(document).ready(function(){
formValidate(); //表单验证函数
});
function formValidate(){
$("#sendmail").validate({ //#sendmail表单id
errorElement : "span", //错误信息将放入此标签内
errorClass: "error_input" , //验证出错时使用的css class
success: "valid" , //自定义验证成功时的动作
errorPlacement: function(error, element) { //自定义错误消息的显示位置
element.next().html(error); //error错误信息,element错误产生的input
},
rules: {
"from":{
required: true
},
"fromName":{
required: true
},
"to":{
required: true
},
"url":{
required: true
},
"subject":{
required: true
},
"html":{
required:true
},
"contry":{
required:true
}
},
messages: {
"from":{
required: '请输入公司名称'
},
"fromName":{
required: '请选择省份'
},
"to":{
required: '请选择城市'
},
"url":{
required: '请选择县/区'
},
"subject":{
required: '请输入地址'
},
"html":{
required:'请选择国家区号'
},
"contry":{
required:'请选择国家区号'
}
},
submitHandler: function(form){ //表单提交句柄,为一回调函数,带一个参数:form
form.submit(); //提交表单
}
});
};
</script>
<style type="text/css">
.error_input{color:red;} //错误提示的样式
</style>
<form action="#" method="post" id="sendmail" name="sendmail">
<p>发件邮箱:<input id="from" placeholder="银行账号" name="from" type="email" required/><span></span></p>
<p>发件姓名:<input id="fromName" placeholder="银行账号" name="fromName" type="text" required/><span></span></p>
<p>收件邮箱:<input id="to" placeholder="银行账号" name="to" type="email" required/><span></span></p>
<p>url:<input id="url" name="url" placeholder="银行账号" type="email" required/><span></span></p>
<p>发件主题:<input id="subject" placeholder="银行账号" name="subject" type="text" required/><span></span></p>
<p>选择类别:<select id="contry" name="contry">
<option value ="中国">中国</option>
<option value ="美国">美国</option>
<option value="日本">日本</option>
<option value="俄罗斯">俄罗斯</option>
<option value="法国">法国</option>
<option value="德国">德国</option>
</select>
<span></span></p>
<p>邮件内容:<textarea id="html" placeholder="银行账号" name="html" cols="120" rows="6" required></textarea><span></span></p>
<p>附 件:<input name="submit" type="submit" value="提交"/></p>
</form>