FormValidation on modal bootstrap - javascript

I have a modal as so
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="page-title">
Add Movie
<small>Note fields marked with <span style="color:red">*</span> are required</small>
</h2>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" id="NewMovie">
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Title <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="Title" name="Title" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Classification <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="Classification" name="Classification" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Rating <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input id="Rating" name="Rating" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="5" data-slider-step="1" data-slider-value="0" /> <span id="rate" style="margin-left:5%">0 / 5</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Release Date <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="ReleaseDate" name="ReleaseDate" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Cast <span style="color:red">*</span>
</label>
<div class="col-sm-5">
<input type="text" class="form-control col-sm-5" id="Cast" />
</div>
<div class="col-sm-1">
<button type="button" id="btnNewCast" class="btn btn-default">+</button>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix"></label>
<div class="col-sm-6" id="newCast">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnAddMovie" data-dismiss="modal">Save</button>
</div>
</div>
</div>
When btnAddMovie is clicked I ajax / jquery method is called which calls a method in my controller. But before I submit I would like to validate the fields they have entered.
I am following this Form validation on bootstrap modal
I have declared my implementation as follows:
$(document).ready(function() {
$('#NewMovie').formValidation({
framework: 'bootstrap',
excluded: [':disabled'],
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
Title: {
validators: {
notEmpty: {
message: 'The Title is required'
}
}
}
}
});
});
My ajax method is as follows:
$("#btnAddMovie").click(function () {
var stringArr = $('span[data-id="cast[]"]').map(function () {
return $(this).text().trim();
}).get();
$.ajax({
url: '/Movies/Add',
traditional: true,
data: { "Title": $("#Title").val(), "Classification": $("#Classification").val(), "Rating": $("#Rating").val(), "ReleaseDate": $("#ReleaseDate").val(), "Cast": stringArr },
cache: false,
type: "POST",
success: function (result) {
if (result.success) {
}
},
error: function (result) {
alert("Error");
}
});
});
But for some reason when ever click the button on my form it automatically posts back without doing the validation?
I'm trying to validate and depending on if its true or false then perform the relevant action.

About your button, either you have to change it to a submit button or use the button setting to indicate which button should trigger the validation (see bellow)
button: {
// The submit buttons selector
selector: '#btnAddMovie'
}
you have to delete data-dismiss="modal" from your button
And then trigger the success.form.fv event and call your ajax method there, see following code:
$('#NewMovie').formValidation({
framework: 'bootstrap',
excluded: [':disabled'],
// ...
icon: {
// ...
},
fields: {
// ...
}
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
// And then
// Place your Ajax call here
var stringArr = $('span[data-id="cast[]"]').map(function () {
return $(this).text().trim();
}).get();
$.ajax({
url: '/Movies/Add',
traditional: true,
data: { "Title": $("#Title").val(), "Classification": $("#Classification").val(), "Rating": $("#Rating").val(), "ReleaseDate": $("#ReleaseDate").val(), "Cast": stringArr },
cache: false,
type: "POST",
success: function (result) {
if (result.success) {
}
},
error: function (result) {
alert("Error");
}
});
// And then close your modal
$('#MyModal').modal('hide');
});
# References:
form events docs: http://formvalidation.io/settings/#event-form
button setting docs: http://formvalidation.io/settings/#form-button

If you remove your ajax call, does the validation work?
Maybe you should take a look at your submit button :
<button type="button" class="btn btn-default" id="btnAddMovie" data-dismiss="modal">Save</button>
which is not a submit button.
If you look to the example in the page you gave us, you can see that the submit button's code is
<button type="submit" class="btn btn-primary">Login</button>
Try to change this and it would be nice if you could provide us a JSFiddle
Hope it's gonna help you a bit.

Related

ajax submit multiple times

I have created an application in the php, I am using the bootstrap model to update user details using AJAX. Now there are two forms: first updates the user's details and adds comments to another user. When I try to submit a form to AJAX and I try to submit a form, it does not work, when i use ajaxComplete function then my form data has been submitted successfully, but at the time it submits the form multiple times at the same time.
$(document).ajaxComplete(function() {
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="card-group-control card-group-control-right" id="accordion-model">
<div class="card">
<form method="post" name="update-user-details" id="update-user-details" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">First Name</label>
<input type="text" class="form-control" placeholder="First Name" name="customer_name" id="customer_name">
</div>
</div>
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Mobile</label>
<input type="text" class="form-control" placeholder="Mobile" name="mobile_number" id="mobile_number">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
<form method="post" name="remarks" id="remarks" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Remarks</label>
<input type="text" class="form-control" placeholder="Remarks" name="remarks" id="remarks">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Move this piece of code outside of your ajaxComplete() function. You are probably somehow triggering the ajaxComplete function multiple times, causing multiple event listeners for the form submit.
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));

jQuery Validation inside Bootstrap modal doesn't fire

Ok so i'm trying to use jQuery Validation to validate my form inside modal. However, my jQuery Validation doesn't even fire at all, not even an error. I already used the debug, and there's a warning:
Nothing selected, can't validate, returning nothing.
These are my codes:
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Form Add Question Category</h4>
</div>
<form id="form_input" method="post" action="">
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<input type="hidden" id="submit_type" name="submit_type" value="address_insert"/>
<div class="form-group">
<div class="col-md-6 col-sm-12 col-xs-12">
<label for="txtDeviceID">Device ID</label>
<input type="text" class="form-control" id="txtDeviceID" name="txtDeviceID" placeholder="Device ID"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
<div class="col-md-6 col-sm-12 col-xs-12">
<label for="txtPassword">Password</label>
<input type="text" class="form-control" id="txtPassword" name="txtPassword" placeholder="Password"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-12 col-xs-12">
<label>Employee</label>
<select class="select2_employee" name="select2_employee" style="width:100%"></select>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-12 col-xs-12">
<label>Branch</label>
<select class="select2_branch" name="select2_branch" style="width:100%"></select>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-6">
<label for="txtIPLocal">IP Local</label>
<input type="text" class="form-control" id="txtIPLocal" name="txtIPLocal" placeholder="IP Local"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<label for="txtPortLocal">Port Local</label>
<input type="text" class="form-control" id="txtPortLocal" name="txtPortLocal" placeholder="Port Local" />
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-6">
<label for="txtIPPublic">IP Public</label>
<input type="text" class="form-control" id="txtIPPublic" name="txtIPPublic" placeholder="IP Public"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<label for="txtPortPublic">Port Public</label>
<input type="text" class="form-control" id="txtPortPublic" name="txtPortPublic" placeholder="Port Public"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-6">
<label for="txtIPAlternative">IP Alternative</label>
<input type="text" class="form-control" id="txtIPAlternative" name="txtIPAlternative" placeholder="IP Alternative"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<label for="txtPortAlternative">Port Alternative</label>
<input type="text" class="form-control" id="txtPortAlternative" name="txtPortAlternative" placeholder="Port Alternative"/>
<div class="error_validation" style="color:red; font-size:9px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" value='Submit' class="btn btn-md btn-primary" >Submit</button>
<button type="button" class="btn btn-md btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
The javascript:
var validate_start = $("#myModal #form_input").validate({
debug: true,
ignore: [],
rules: {
txtDeviceID: {
required: true
// lettersOnlySpace: true,
// minlength: 5,
// maxlength: 15
},
txtPassword: {
required: true
},
select2_employee: {
required: true
},
select2_branch: {
required: true
},
txtIPLocal: {
required: true
},
txtPortLocal: {
required: true,
number: true,
range: [1, 65535]
},
txtIPPublic: {
required: true
},
txtPortPublic: {
required: true,
number: true,
range: [1, 65535]
},
txtIPAlternative: {
required: true
},
txtPortAlternative: {
required: true,
number: true,
range: [1, 65535]
}
},
// messages: {
// txtDeviceID: {
// required: "Input required."
// },
// txtPassword: {
// required: "Input required."
// },
// select2_employee: {
// required: "Input required."
// },
// select2_branch: {
// required: "Input required."
// },
// txtIPLocal: {
// required: "Input required."
// },
// txtPortLocal: {
// required: "Input required."
// },
// txtIPPublic: {
// required: "Input required."
// },
// txtPortPublic: {
// required: "Input required."
// },
// txtIPAlternative: {
// required: "Input required."
// },
// txtPortAlternative: {
// required: "Input required."
// }
// },
errorPlacement: function (error, element) {
console.log("validate success!");
error.appendTo(element.siblings('.error_validation'));
},
submitHandler: function (form) {
console.log(form);
// $.ajax({
// url: $("#submit_type").val(),
// type: 'POST',
// dataType: 'JSON',
// data: function (params) {
// console.log("parameter");
// console.log(params);
// return JSON.stringify($(form).serialize());
// },
// // data: $(form).serialize(),
// success: function () {
// // $(form).html("<div id='message'></div>");
// // $('#message').html("<h2>Your request is on the way!</h2>")
// // .append("<p>someone</p>")
// // .hide()
// // .fadeIn(1500, function () {
// // $('#message').append("<img id='checkmark' src='images/ok.png' />");
// // });
// }
// });
return false; // required to block normal submit since you used ajax
},
invalidHandler: function (event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
console.log("error " + errors);
}
});
I've already tried many solution, from fixing the form inside modal body, use the unobstrusive library, but it still doesn't want to fire. Please help me, one lead to trigger the validation is enough, i will follow afterwards.
Thankyou.
Try to init the validation code right after the modal is shown. If you have something like $('#myModal').open(), then you have to init the validation after the open method. I believe it is something related to the DOM manipulation.

how to resolve form[0].submit is not a function(…)

i have problem with validate submit button.
so here my code:
var handleValidation = function() {
var form = $('#form-date');
var error = $('.alert-danger', form);
var success = $('.alert-success', form);
form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
rules: {
start: {
required: true,
date: true,
remote: {
url: "<?php echo site_url('activity/check_date')?>",
type: "post",
data: {
start: function(){ return $("#date").val(); }
}
}
},
end: {
required: true,
date: true,
remote: {
url: "<?php echo site_url('activity/check_end')?>",
type: "post",
data: {
end: function(){ return $("#end").val(); }
}
}
},
},
messages: {
start:
{
remote: 'Date already in use.'
},
end:
{
remote: 'Date already in use.'
},
},
invalidHandler: function (event, validator) { //display error alert on form submit
success.hide();
error.show();
App.scrollTo(error, -200);
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.form-group').removeClass('has-error'); // set error class to the control group
},
success: function (label) {
label
.closest('.form-group').removeClass('has-error'); // set success class to the control group
},
submitHandler: function (form) {
success.show();
error.hide();
form[0].submit(); // submit the form
}
});
}
<form class="form-horizontal" id="form-date" role="form" method="post" action="<?php echo base_url(); ?>activity/add">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
You have some form errors. Please check below.
</div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button>
Your form validation is successful!
</div>
<input type="hidden" class="form-control" name="nik" value="<?php echo $this->session->userdata('nik')?>">
<div class="form-group">
<label class="col-sm-3 control-label">Start Date:<span
class="required">*</span> </label>
<div class="col-sm-7">
<div class="input-group date date-picker" data-date-format="yyyy-mm-dd">
<input type="text" class="form-control" readonly id="date" name="start" required>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">End Date:<span
class="required">*</span> </label>
<div class="col-sm-7">
<div class="input-group date date-picker" data-date-format="yyyy-mm-dd">
<input type="text" class="form-control" readonly id="end" name="end" required>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-5">
<button type="submit" class="btn green">
<i class="fa fa-pencil"></i> Create</button>
<button type="button" class="btn default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
i have validate where data is empty show warning,but if data succesful.only show warning success and didn't redirect.in console error show
form[0].submit is not a function(…)
so where is wrong code.
how to resolve it?
Just change :
form[0].submit();
To
form.submit();
The form argument of submitHandler() is the dom element not a jQuery object and per plugin docs should be submitted using native submit

jquery validation plugin ajax submit not working

I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is not working also the form cannot send out.
bootstrap modal form
<div class="modal fade" id="form-content" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">
×
</button>
<h3>send message</h3>
</div>
<div class="modal-body">
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic:</label>
<input class="form-control" type="text" name="topic">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label ">ruser: </label>
<input class="form-control" type="text" name="ruser">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit">send</button>
close
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<button class="btn btn-success btn-lg" data-toggle="modal"
data-target="#form-content">
send message
</button>
javascript
$(document).ready(function(){
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages : {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter ruser'
},
content: {
required: 'enter content'
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function(msg){
if(msg=='no'){
alert(msg);
}
else if(msg=='ok!'){
alert(msg);
location.reload()
}
},
error: function(){
alert("failure");
}
});
return false;
}
});
});
How can i fix the problem?
The jsfiddle
The problem is the submit button is not a descendant of the form you are trying to submit.
One possible solution is to write a click handler for the button, and call the form submit from there like
<div class="modal-footer">
<button class="btn btn-success" id="submitcontact">send</button>
close
</div>
then
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Demo: Fiddle
Firstly, As your Jquery code has one error:
On line no. 40 :- } replace with },
And solution is to call a function on onclick event of your button. No need to remove type="submit" as it's removed in Arun's answer.
Inside $(document).ready(function() write below function:
$('#sendForm').click(function(){
$('form.contact').submit();
})
And it will work. WOKRING DEMO

bootstrapValidator ajax request, prevent closing bootstrap modal after submitting

hi im using bootstrapValidator to validate my form and i have no idea where to add ajax request after validating form. and also want to prevent closing bootstrap modal after submitting the form. i referred similar questions and still couldn't make it work.
here is my bootstrap modal
<a href="#"class="btn btn-lg btn-black ico-windows" data-backdrop="static" data-keyboard="false" data-toggle="modal" data-target="#AddAlbum" > Create New Album </a>
<!-- Modal -->
<div class="modal fade" id="AddAlbum" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Create New Album</h4>
</div>
<div class="modal-body">
<div id="formregister">
<form action="" class="form-horizontal" role="form" id="newAlbum" >
<p class="qc-errmsg" style="display: none;"> </p>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Album Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" name="albumName" placeholder="Album Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label" >Description</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" onclick="send()" value="cart" class="btn btn-primary">Save Changes</button>
</div>
</div>
</form>
</div> <!-- form register -->
<div id="successfulpost" style="font: bold 12px Verdana, Arial, Helvetica, sans-serif; color: #ff0000; display: none;">
<p class="jst-txt"><span>Thank you,</span> for showing your Interest !!</p>
<p class="jst-txt">Our property advisor shall get in touch with you very shortly..</p>
</div>
</div> <!-- model body-->
</div>
</div>
</div>
here is my javascript
$(document).ready(function () {
//validations
$('#newAlbum').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
albumName: {
message: 'The Album Name is not valid',
validators: {
notEmpty: {
message: 'The Album Name is required and cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The Album Name must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9]+$/,
message: 'The Album Name can only consist of alphabetical and number'
}
},
//form.submit();
}
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
url: "add_album.php",
type: "POST",
success: function () {
alert('done');
$('#newAlbum').hide();
$('#successfulpost').show();
}
});
});
i made a jsbin for this
http://jsbin.com/xatog/8/edit?html,js,output
You are using version 0.5.3. They have removed the submithandler option and added an event success.form.bv.
$(form)
.bootstrapValidator(options)
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
validator = $form.data('bootstrapValidator'),
submitButton = validator.getSubmitButton();
// Do whatever you want here ...
});
source here
Fiddle here

Categories

Resources