CSS页面代码:
<style>
.submit{
margin: 5px;
}
</style>
HTML页面代码:
<form action="#" method="post" id="form">
<div id="year">年份:
<input type="text" name="year" class="control">
<span class="hint"></span>
</div>
<div id="month">月份:
<input type="text" name="month" class="control">
<span class="hint"></span>
</div>
<div>
<input type="submit" class=submit value="查询">
</div>
</form>
JS页面代码:
<script>
function trim(str){
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
function checkVal(ele, reg, msg) {
let _value = trim(ele.value);
let _hint = ele.parentNode.children[1];
if (!_value.match(reg)) {
ele.style.border = '1px solid #f00';
_hint.innerHTML = msg;
return false;
}
_hint.innerHTML = '';
return true;
}
function checkControl(obj, reg, msg) {
obj.getElementsByClassName('control')[0].onfocus = function () {
this.style.border = '';
}
obj.getElementsByClassName('control')[0].onblur = function () {
checkVal(this, reg, msg);
}
}
let _year = document.getElementById('year');
let _month = document.getElementById('month');
let _form = document.getElementById('form');
checkControl(_year, /^\d{4}$/, '年份输入错误');
checkControl(_month, /^((0?[1-9])|(1[012]))$/, '月份输入在1-12之间');
_form.onsubmit = function () {
let _year_control = _year.getElementsByClassName('control')[0];
let _year_val = _year_control.value;
let _month_control = _month.getElementsByClassName('control')[0];
let _month_val = _month_control.value;
let _year_hint_val = _year.getElementsByClassName('hint')[0].innerHTML;
let _month_hint_val = _month.getElementsByClassName('hint')[0].innerHTML;
if (_year_val && _month_val) {
return !_year_hint_val && !_month_hint_val;
}
return false;
}
</script>
运行结果如图: