我正在尝试使用下面给出的代码验证Bootstrap multiselect下拉列表,表单已经过验证,但我没有得到正确的输出, 验证消息在选择框上方,消息在时间成倍增加 单击提交按钮,选择选项后,消息没有被删除。请帮助解决我的问题。
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("needsSelection", function (value, element) {
var count = $(element).find('option:selected').length;
return count > 0;
});
$.validator.messages.needsSelection = 'Select Atleast One College';
$("#User").validate({
rules: {
'college[]': {
needsSelection: true
}
},
}
});
$("#submit").click(function(e) {
var isvalidate=$("#User").valid();
if(isvalidate=="true")
{
}
else
{
$("#User").submit();
}
});
});
<form id="User" name="User" method="post" enctype="multipart/form-data" action="index">
<select data-placeholder="Choose College Name" name="college[]" class="chosen-select" id="college" multiple tabindex="4">
<option value=""></option>
<option value="1">abc</option>
<option value="2">abc1</option>
</select>
<a id="submit">Submit</a>
</form>
答案 0 :(得分:1)
This is not a direct answer to your question, but may provide a solution to your problem.
First, change the anchor tag to a button -- because anchor tags have built-in navigation behaviour that you must counter (event.preventDefault()
) and therefore add needless complexity. How about a button (input or button tags) or a div tag, or a p?)
Next, a simpler structure to evaluating your form:
HTML: (just changed your anchor submit button to:
<input id="dosubmit" type="submit" value="Submit" />
Note: do not use "submit" as the id for a submit button, as that is a reserved keyword
javascript/jQuery:
$('#User').submit(function(e){
var col = $('#college').val();
if ( col==null || col=='' || col=='Please choose one:' ){
$('#college').css('background','yellow').focus();
return false;
}else{
$('#college').css('background','transparent');
alert('Form submitted');
//continue to submit the form - but not now
return false;
}
});
Please consider this verification script for your project.
答案 1 :(得分:0)
这不是您问题的答案,但我会建议您并鼓励您一起使用服务器端验证。
您的数据应该在接收ajax调用的php文件中进行验证并根据需要进行清理。
如果出现问题,响应将始终传回您的表单,为您的用户提供所需的反馈。
您可以在互联网上找到许多如何执行此操作的示例。
请在此处查看示例:https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
所以回顾一下:不要进行客户端验证!!