前端提交表单两种验证方式记录 jq或h5 required属性

时间:2022-05-30 19:00:25

JQuery:

<form id="form">
<input type="text" name="aaa">
<select name="bbb">
<option value="">请选择</option>
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
</select>
<button type="button" id="submit">提交</button>
</form>
//提交表单
$('#submit').click(function(){
var data = {};
var t = $('#form').serializeArray();
$.each(t, function() {
data [this.name] = this.value;
});
console.log(data);
if(data.aaa == ''){alert("aaa不能为空!");return false;}
if(data.bbb == ''){alert("bbb不能为空!");return false;}
$('#form').submit();
});

HTML5 required属性:

<input type="text" name="aaa" required="required">
<select name="bbb" required="required">
<option value="">请选择</option>
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
</select> <button type="submit">提交</button>