[英]Form validation on modal confirm
This is my code. 这是我的代码。 The problem is that the form is submitting when i clicked the confirm button on the modal.
问题是,当我单击模式上的确认按钮时,表单正在提交。 The thing is I dont know how to validate the form first before submitting.
问题是我不知道如何在提交之前先验证表单。 This is the process I want.
这是我想要的过程。
1. The user fill up the field. 1.用户填写该字段。
2. The user click confirm button (at least here it the form must be validated) or here 3. The modal shows and when I clicked the submit button the modal will close then the form validations will show 2.用户单击确认按钮(至少在此必须验证表单)或在此处3.模态显示,当我单击提交按钮时,模态将关闭,然后将显示表单验证
<form role="form" id="formfield" action="<?php echo base_url()?>Shop/add_shop" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<p><B>Shop name:</b></p>
<input type="text" class="form-control" id ="shop_name" name="shop_name">
</div>
<div class="col-md-1"></div>
</div>
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<form action="<?php echo base_url()?>Shop/add_shop" id="wew" method="post">
<div class="modal-body">
Are you sure you want to submit the following details?
<table class="table">
<tr>
<th>Shop Name: </th>
<td ><input type="text " id="s_name" name="shop_name" readonly></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button href="#" onclick="document.getElementById('formfield').submit();" class="btn btn-success success">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$('#submitBtn').click(function() {
$('#s_name').val($('#shop_name').val());
});
$('#submit').click(function(){
$('#formfield').submit();
});
</script>
You need to handle the form submit event, and do your validation in there. 您需要处理表单提交事件,并在那里进行验证。
In the example below, the form will not be submitted unless isValid
is true
在下面的示例中,除非
isValid
为true
否则不会提交表单
$("form").submit(function(event) {
isValid = false; // form is not valid
if(isValid != true) event.preventDefault(); // prevent the submission
});
You can determine if a field is empty like so: 您可以像这样确定一个字段是否为空:
if($("input[name=shop_name]").val() == '') alert('Shop name cannot be empty!');
There are also really good validation libraries which are pre-built. 还有一些非常好的预构建的验证库。 My personal favorite is validate.js which is available at http://jqueryvalidation.org/ Using a prebuilt library like that one allows you to simply do something like
$("form").validate();
我个人最喜欢的是validate.js,可从http://jqueryvalidation.org/获得。使用这样的预构建库,您可以简单地执行
$("form").validate();
and it's very easy to extend with custom rules if you don't like what they have available for use. 如果您不喜欢自定义规则,可以很容易地对其进行扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.