我正在使用jquery,bootstrap和select2。当字段验证失败时,其边框将变为红色。但是,对于 SELECT 输入类型,当多个为真时,它不起作用。验证仍然会发生,但不会直观地反映出来,从而使用户对需要填写哪个字段感到困惑。(实际表单使用数十个字段,这只是一个愚蠢的例子(
我已经用谷歌搜索了很多,但还没有找到明确的解决方案。我不知道为什么错误类会在单个和多个选择之间以任何不同的方式针对下拉选择组件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie-edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Testing App</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/bootstrap3.3.5/bootstrap.min.js" ></script>
<script type="text/javascript" src="js/jquery.validate.min.js" ></script>
<script type="text/javascript" src="js/select2/select2.js" ></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap3.3.5/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="js/select2/select2.css" />
<link rel="stylesheet" type="text/css" href="css/select2-bootstrap.css" />
<style>
input.error, select.error,
div.error a.select2-choice,
textarea.error {
border-color: red !important;
color: red !important;
}
.select2.error {
border-color: red !important;
color: red !important;
}
span.error{
outline: dotted;
border: 1px solid #800000;
box-shadow: 0 0 5px 1px #800000;
}
</style>
<script lang="text/javascript">
$(document).ready(function() {
$('#thing').select2({minimumResultsForSearch: -1});
$('#stuff').select2({minimumResultsForSearch: -1});
$('#frmCreateEquipment').validate({
ignore: [],
rules : {
thing : "required",
stuff : "required",
}
});
$('#send').on('click', function(e){
e.preventDefault();
if ($('#frmCreateEquipment').valid()){
console.log('ok');
}else{
console.log('fail');
}
});
});
</script>
</head>
<body>
<div class="container">
<form id="frmCreateEquipment" action="javascript:void(0);">
<div class="row">
<div class="col-md-4">
<label for="stuff" >Stuff:</label>
<select id="stuff" name="stuff">
<option value=""></option>
<option value="1">aereae</option>
<option value="-1">Noy55yayne</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="thing" >Things:</label>
<select id="thing" name="thing" multiple="multiple" required>
<option value=""></option>
<option value="1">fluid</option>
<option value="-1">None</option>
</select>
</div>
</div>
<button id="send"name="send"type="submit">send</button>
</form>
</div>
</body>
</html>
不完全是一个强大的解决方案,但只有一个元素来挑出它会起作用。 我将在线找到的修复程序仅应用于给我带来麻烦的元素,否则我只使用验证插件中的原始代码。
$('#frmCreateEquipment').validate({
ignore: [],
rules : {
thing : "required",
stuff : "required",
},
highlight: function( element, errorClass, validClass ) {
if(element.id == "thing"){
var e = $(element);
if (e.hasClass('select2-offscreen')){
$('#s2id_'+e.attr('id')+' ul').addClass(errorClass);
}
}else{
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
}
},
});