Form validation and all subsequent code doesn't execute - javascript

I have an update form,that i call inside a modal on my main page,(with an onclick event,the click triggers a call with xmlhttprequest for the edit page containing the form with the stored data values). The thing is,everything works fines,the update works,post works,retrieving data in the first place works,except for the form validation,and ajax use to post the data. Please notice that on my main page,i have a create call,that creates a new instance,and it works just fine,with the form validation and the ajax post,so it can't be some required jQuery or any other script.
This is my form:
<form id="eventFormUpdate" method="POST" class="form-horizontal" action="Event/{{$event->id}}/Update">
<input type="hidden" name="_method" value="PATCH" id="hidden-update">
<div class="form-group">
<label class="col-xs-3 control-label">Nom</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="nameUpdate" value="{{$event->name}}"/>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Date de début</label>
<div class="col-xs-5 dateContainer">
<div class="input-group input-append date" id="startDatePickerUpdate">
<input type="text" class="form-control" name="starting_dateUpdate" value="{{$event->starting_date}}"/>
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Date de fin</label>
<div class="col-xs-5 dateContainer">
<div class="input-group input-append date" id="endDatePickerUpdate">
<input type="text" class="form-control" name="ending_dateUpdate" value="{{$event->ending_date}}"/>
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Assigné à</label>
<div class="col-xs-5 selectContainer">
<select name="assigned_toUpdate" class="form-control">
<option value="4" selected >First</option> <!--fix this by checking if is the selected data or not-->
</select>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Description</label>
<div class="col-xs-5">
<textarea id="descUpdate" class="form-control" name="descriptionUpdate" placeholder="Veuillez entrer une description">{{$event->description}}</textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default" id="update-event-submit">valider</button>
</div>
</div>
</form>
And here is my script that handles the form validation and the ajax posting
<!-- event update script -->
<script>
$(document).ready(function() {
$('#startDatePickerUpdate')
.datepicker({
format: 'yyyy/mm/dd'
})
.on('changeDate', function(e) {
// Revalidate the start date field
$('#eventFormUpdate').formValidation('revalidateField', 'starting_dateUpdate');
});
$('#endDatePickerUpdate')
.datepicker({
format: 'yyyy/mm/dd'
})
.on('changeDate', function(e) {
$('#eventFormUpdate').formValidation('revalidateField', 'ending_dateUpdate');
})
.find('[name="assigned_toUpdate"]')
.selectpicker()
.change(function(e) {
/* Revalidate the pick when it is changed */
$('#eventFormUpdate').formValidation('revalidateField', 'assigned_toUpdate');
})
.end();
$('#eventFormUpdate')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nameUpdate: {
validators: {
notEmpty: {
message: 'Le nom est obligatoire.'
}
}
},
starting_dateUpdate: {
validators: {
notEmpty: {
message: 'La date de début est obligatoire.'
},
date: {
format: 'YYYY/MM/DD',
min: new Date(new Date().setDate(new Date().getDate()-1)),
max: 'ending_date',
message: 'La date de début est non valide.'
}
}
},
ending_dateUpdate: {
validators: {
notEmpty: {
message: 'La date est oligatoire.'
},
date: {
format: 'YYYY/MM/DD',
min: 'starting_date',
message: 'La date de fin est non valide.'
}
}
},
descriptionUpdate: {
validators: {
notEmpty: {
message: 'La description est obligatoire.'
}
}
},
assigned_toUpdate: {
validators: {
notEmpty: {
message: 'Veuillez séléctionner un utilisateur.'
}
}
}
}
})
.on('success.field.fv', function(e, data) {
if (data.field === 'starting_dateUpdate' && !data.fv.isValidField('ending_dateUpdate')) {
// We need to revalidate the end date
data.fv.revalidateField('ending_dateUpdate');
}
if (data.field === 'ending_dateUpdate' && !data.fv.isValidField('starting_dateUpdate')) {
// We need to revalidate the start date
data.fv.revalidateField('starting_dateUpdate');
}
})
.submit(function(){
return false;
})
.submit(function(){
console.log('gonnastartsub');
var $form = $("#eventFormUpdate"),
url = $form.attr('action');
console.log('got vars');
$.post(url, $form.serialize()).done(function () {
console.log('am in');
$("#modal-closeUpdate").click();
console.log('posted');
});
});
});
$("#descUpdate")
.focus(function() {
if (this.value === this.defaultValue) {
this.value = '';
}
})
.blur(function() {
if (this.value === '') {
this.value = this.defaultValue;
}
});
Update
This is my controller
public function update(Request $request,$id)
{
$event = event::find($id);
$event->name = $request->name;
$event->description = $request->description;
$event->starting_date = $request->starting_date;
$event->ending_date = $request->ending_date;
$event->assigned_to = $request->assigned_to;
$event->save();
}
And this My routes call:
Route::patch('Event/{eventID}/Update', 'EventsController#update');
One last thing,at first the script was on my main page,and it didn't work so i tried to put it in in the called page with xmlhttprequest,and still doesn't work.
The only thing i can think of is,when i call the new page(the form to edit and update data) the script is already loaded in the main page,so it doesn't find the ids of the elements to handle,that's why it does not work,or at least this is the only reason i could find .
Any suggestions please?

Well first of all you have an error in your datepickers min and max,they don't match the field names you have set,set them to this
max: 'ending_dateUpdate'
min: 'starting_dateUpdate'
Second,the field names in your form,don't match those on your controller page,so it can't really update if it can't find the data,this should be your controller page:
public function update(Request $request,$id)
{
$event = event::find($id);
$event->name = $request->nameUpdate;
$event->description = $request->descriptionUpdate;
$event->starting_date = $request->starting_dateUpdate;
$event->ending_date = $request->ending_dateUpdate;
$event->assigned_to = $request->assigned_toUpdate;
$event->save();
}
Hope it helps .

Related

bootstrap form validation only one field required

I have a form that has userID and screen name input fields.
When validating I need to make sure that at least one of them is entered (if both were entered I only take one). The html:
this.addFormValidators = function () {
$('#editCreatePipeForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
ConsumerKey: {
validators: {
notEmpty: {
message: 'The Consumer Key is required'
}
}
},
ConsumerKeySecret: {
validators: {
notEmpty: {
message: 'The Consumer Key Secret is required'
}
}
},
CollectionIntervalSec: {
validators: {
notEmpty: {
message: 'The collection interval is required'
},
between: {
message: 'The collection interval must be a number greater than 10',
min: 10,
max: 1000000000
}
}
},
//KeepHistoricalDataTimeSec: {
// validators: {
// notEmpty: {
// message: 'The retain data value is required'
// },
// between: {
// message: 'The retain data value must be a number greater than 1000',
// min: 1000,
// max: 1000000000
// }
// }
//},
Description: {
validators: {
stringLength: {
max: 500,
message: 'The description must be less than 500 characters long'
}
}
}
}
}, null);
};
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ScreenName" class="col-md-4 YcdFormLabel" title="screen name of user to retrieve">Screen name</label>
<div class="col-md-8">
<input type="text" placeholder="Screen Name" class="form-control user" autocomplete="off"
name="screenName"
id="screenName" data-bind="value: screenName, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"/>
<div class="col-md-6">
<div class="form-group">
#*<div class="col-md-8">*#
<label for="or" class="col-md-10">or</label>
#*</div>*#
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userID" class="col-md-4 YcdFormLabel" title="user_ID of user to retrieve">User ID</label>
<div class="col-md-8">
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off"
name="userID"
id="userID" data-bind="value: userID, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
I added another function which I called it before submitting instead of using Bootstrap and jQuery form validation.
private hasTimelineAndUsername = (): boolean => {
if (this.viewModel.searchSelection() == "timeline"
&& ((this.viewModel.userID() == "" ||
this.viewModel.userID() == null) &&
(this.viewModel.screenName() == "" ||
this.viewModel.screenName() == null))) {
return false
}
return true;
}
The submitting function:
public getCollectionParameters() {
var fv = $('#editCreatePipeForm').data('formValidation')
fv.validate();
var isValid = fv.isValid();
if (!isValid) {
toastr.error("Please fix all problems before saving");
return null;
}
if (!this.hasTimelineAndUsername()) {
toastr.clear();
toastr.error("Please type username/userID");
return null;
}
if (!this.validateData()) {
return null;
}
return JSON.stringify(ko.mapping.toJS(this.viewModel));
}
I hope my code will help you.
JSFiddle: https://jsfiddle.net/aice09/3wjdvf30/
CodePen: https://codepen.io/aice09/pen/XgQyem
GitHub: https://github.com/Ailyn09/project102/blob/master/chooseintwoinput.html
function verify() {
var screenName = document.getElementById("screenName").value;
var userID = document.getElementById("userID").value;
if (userID === '' && screenName === '') {
alert('Add value to any field');
}
if (userID !== '' && screenName === '') {
alert('Your screen name are currently empty. The value you will be taken is your screen name');
document.getElementById("takedvalue").value = userID;
}
if (userID === '' && screenName !== '') {
alert('Your user id are currently empty. The value you will be taken is your user identification');
document.getElementById("takedvalue").value = screenName;
}
if (userID !== '' && screenName !== '') {
document.getElementById("mainbtn").style.display = "none";
document.getElementById("backbtn").style.display = "initial";
document.getElementById("choosescreenName").style.display = "initial";
document.getElementById("chooseuserID").style.display = "initial";
}
}
//Reset Form
$('.backbtn').click(function () {
document.getElementById("mainbtn").style.display = "initial";
document.getElementById("backbtn").style.display = "none";
document.getElementById("choosescreenName").style.display = "none";
document.getElementById("chooseuserID").style.display = "none";
});
//Choose First Input
$('.choosescreenName').click(function () {
var screenName = document.getElementById("screenName").value;
document.getElementById("takedvalue").value = screenName;
});
//Choose Second Input
$('.chooseuserID').click(function () {
var userID = document.getElementById("userID").value;
document.getElementById("takedvalue").value = userID;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div class="container">
<form action="POST">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="screenName">Screen name</label>
<input type="text" placeholder="Screen Name" class="form-control " autocomplete="off" name="screenName" id="screenName" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="userID">User ID</label>
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off" name="userID" id="userID" />
</div>
</div>
<div class="col-md-12">
<button type="button" class="btn btn-primary" id="mainbtn" onclick="verify();">SUBMIT</button>
<button type="reset" class="btn btn-primary backbtn" id="backbtn" style="display:none;">BACK</button>
<button type="button" class="btn btn-primary choosescreenName" id="choosescreenName" style="display:none;">CHOOSE SCREEN NAME</button>
<button type="button" class="btn btn-primary chooseuserID" id="chooseuserID" style="display:none;">CHOOSE USER ID</button>
</div>
<div class="col-md-12">
<hr>
<div class="form-group">
<label for="userID">Value</label>
<input type="text" placeholder="Taken Value" class="form-control" id="takedvalue" readonly />
</div>
</div>
</div>
</form>
</div>

bootstrapValidator Validating multiple inputs as one not working

On my login view. I am using bootstrap validator https://github.com/nghuuphuoc/bootstrapvalidator/tree/v0.5.2. For the php side of thing I use codeigniter MVC framework 3.0.3
I have to input fields called username and password and one hidden input field called user_info.
With bootstrap validator what I am tring to do is validate multple input fields as one.
But keep on getting this fire bug error below
Image
Here is my login form
<?php echo $header;?>
<?php echo form_open_multipart('admin/common/login', array('id' => 'login-form','role' => 'form'));?>
<div class="row" id="login-panel">
<div class="col-lg-offset-3 col-lg-6 col-md-offset-3 col-md-6 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title"><?php echo $heading_title;?></h1>
</div>
<div class="panel-body">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="fa fa-user"></i></span>
<input type="text" name="username" class="form-control" value="" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon2"><i class="fa fa-lock"></i></span>
<input type="password" name="password" class="form-control" value="" placeholder="Password">
</div>
</div>
<input type="hidden" name="user_info" />
</div><!-- . panel-body -->
<div class="panel-footer">
<div class="text-right">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</div><!-- . panel-footer -->
</div><!-- . panel panel-default -->
</div>
</div><!-- # login-panel -->
<?php echo form_close();?>
<script type="text/javascript">
$(document).ready(function() {
$('#login-form')
.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
user_info: {
excluded: false,
validators: {
notEmpty: {
message: 'Please fill out each field'
}
}
}
}
})
.on('keyup', 'input[name="username"], input[name="password"]', function(e) {
var y = $('#login-form').find('[name="username"]').val(),
m = $('#login-form').find('[name="password"]').val(),
// Set the user_info field value
$('#login-form').find('[name="user_info"]').val(y === '' || m === '' ? '' : [y, m].join('.'));
// Revalidate it
$('#login-form').bootstrapValidator('revalidateField', 'user_info');
});
});
</script>
<?php echo $footer;?>
Question: How can I make bootstrap validator validate multiple input fields as one correctly?
Keep a ; instead of , here:
m = $('#login-form').find('[name="password"]').val(),
Script:
$(document).ready(function() {
$('#login-form')
.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
user_info: {
excluded: false,
validators: {
notEmpty: {
message: 'Please fill out each field'
}
}
}
}
})
.on('keyup', 'input[name="username"], input[name="password"]', function(e) {
var y = $('#login-form').find('[name="username"]').val(),
m = $('#login-form').find('[name="password"]').val(); //<= keep ; here
// Set the user_info field value
$('#login-form').find('[name="user_info"]').val(y === '' || m === '' ? '' : [y, m].join('.'));
// Revalidate it
$('#login-form').bootstrapValidator('revalidateField', 'user_info');
});
});
Here is what I get in their website . It uses the concept of adding a hidden field and combining data into the hidden field. Then we can validate the new hidden field like regular field.
Hope this helps.

validator: onSuccess to return true or false not excuting

I've been trying to have function validation return true or false on success and on error which is being requested by another function, in order to show save confirmation modal or not on Error but its not returning anything or not even executing once return line is read. Validate function does not seem to return anything.
If someone could help me please.
validate function:
<script type="text/javascript">
function validate(){
$('#enableForm')
.bootstrapValidator({
feedbackIcons: {
required: 'glyphicon glyphicon-asterisk',
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
firstname: {
selector:'#firstName',
validators: {
notEmpty: {
message: 'The first name is required and cannot be empty'
}
}
},
lastname: {
selector:'#lastName',
validators: {
notEmpty: {
message: 'The last name is required and cannot be empty'
}
}
},
birthdate: {
selector:'#birthDate',
validators: {
notEmpty: {
message: 'The birth date is required and cannot be empty'
},
date: {
format: 'MM/DD/YYYY',
message: 'The value is not a valid date'
}
}
}
},
onSuccess:function () {
return true;
},
onError: function(){
return false;
}
});
}
</script>
Click function
<script type="text/javascript">
$(function(){
$('#savePatient').click(function(event){
if (validate()){
$('#modal-1').modal('show');
event.preventDefault();
var button = this;
window.setTimeout(function(form){
$(form).submit();
$('#modal-1').modal('hide');
}, 1500, $(button).closest('form'));
}
});
});
</script>
HTML
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="assets/js/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="assets/css/bootstrap.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css"/>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/js/bootstrapValidator.min.js"> </script>
<script src="assets/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<title>Patients Profile</title>
</head>
<body>
<div class="se-pre-con"></div>
<div id="includedContent"></div>
<section>
<div class="jumbotron">
<div class="container">
<div id="includedLogout"></div>
<h1>Patients</h1>
<p>Patient Profile</p>
</div>
</div>
</section>
<div class="container">
<form:form id="enableForm" commandName="patient" class="form-horizontal">
<legend>Add Patients</legend>
<div class="form-group">
<label class="col-sm-1 comp-xs" for="firstName">First Name</label>
<div class="col-sm-2"><form:input cssClass="form-control comp-xs" id="firstName" path="firstName" type="text"/></div>
<label class="col-sm-1 comp-xs" for="middleIni">Middle Initial</label>
<div class="col-sm-1"><form:input cssClass="form-control comp-xs" id="middleIni" path="middleIni" type="text"/></div>
<label class="col-sm-1 comp-xs" for="lastName">Last Name</label>
<div class="col-sm-2"><form:input cssClass="form-control comp-xs" id="lastName" path="lastName" type="text"/></div>
</div>
<div class="form-group">
<label class="col-sm-1 comp-xs" for="address">Address</label>
<div class="col-sm-4"><form:input cssClass="form-control comp-xs" id="address" path="address" type="text"/></div>
<label class="col-sm-2 comp-xs" for="middleIni">Apt No. | Suite No. | Unit No.</label>
<div class="col-sm-1"><form:input cssClass="form-control comp-xs" id="address2" path="address2" type="text"/></div>
</div>
<div class="form-group">
<label class="col-sm-1 comp-xs" for="city">City</label>
<div class="col-sm-2"><form:input cssClass="form-control comp-xs" id="city" path="city" type="text"/></div>
<label class="col-sm-1 comp-xs" for="state">State</label>
<div class="col-sm-1"><form:input cssClass="form-control comp-xs" id="state" path="state" type="text"/></div>
<label class="col-sm-1 comp-xs" for="zipCode">Zip Code</label>
<div class="col-sm-2"><form:input cssClass="form-control comp-xs" id="zipCode" path="zipCode" type="text"/></div>
</div>
<div class="form-group">
<label class="col-sm-1 comp-xs" for="birthDate">Birth Date</label>
<div class="col-sm-2">
<fmt:formatDate var="fmtDate" value="${patient.birthDate}" pattern="MM/dd/yyyy"/>
<form:input cssClass="form-control comp-xs" placeholder="MM/DD/YYY" id="birthDate" path="birthDate" value="${fmtDate}" type="text" class="form:input-large"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="submit" id="savePatient" class="btn btn-primary pull-right" value ="Save" />
</div>
</div>
<div class="modal fade" id="modal-1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header modal-header-saved">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h1><i class="glyphicon glyphicon-thumbs-up"></i> Data Saved</h1>
</div>
</div>
</div>
</div>
</form:form>
</div>
<script>
$(function(){
$("#includedLogout").load("logout.jsp");
$("#includedContent").load("navbar.jsp");
});
</script>
/body>
</html>
UPDATE
#Arkni placed the validator inside the $(document).ready(...) used the following code below but modal keeps looping and showing and hiding and form is not submitting. Thank you again for your help.
onSuccess: function (e) {
// Stop form submission
e.preventDefault();
$('#modal-1').modal('show');
window.setTimeout(function(form) {
$(form).submit();
$('#modal-1').modal('hide');
}, 1500, $('#savePatient').closest('form'));
}
Before proceeding in solving the problem, you have to know that:
According to jQuery Events: Stop (Mis)Using Return False, returning false inside an event handler performs three tasks when called:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
Returning true inside an event handler will not stop event propagation, but Stops callback execution and returns immediately when called.
I suggest you to use one of the following solutions instead of $('#savePatient').click(function(event){ ... }); and function validate() { ... }:
# Solution 1: Using the onSucess handler
$(document).ready(function () {
$('#loginForm')
.bootstrapValidator({
excluded: ':disabled',
feedbackIcons: {
// ...
},
fields: {
// ...
},
onSuccess: function (e) {
// Stop form submission
e.preventDefault();
$('#modal-1').modal('show');
window.setTimeout(function(form) {
$(form).submit();
$('#modal-1').modal('hide');
}, 1500, $('#savePatient').closest('form'));
}
});
});
# Solution 2: Using the event success.form.bv
$(document).ready(function () {
$('#loginForm')
.bootstrapValidator({
excluded: ':disabled',
feedbackIcons: {
// ...
},
fields: {
// ...
}
})
// This event triggered when the form is valid
// It's the equivalent to using the `onSuccess` handler
.on('success.form.bv', function (e) {
e.preventDefault();
$('#modal-1').modal('show');
window.setTimeout(function(form) {
$(form).submit();
$('#modal-1').modal('hide');
}, 1500, $('#savePatient').closest('form'));
});
});
# Working example:
As I can see, you are using Spring MVC, that's why I used the rendered HTML markup in order to create a demo, see http://jsfiddle.net/Arkni/kxxua2f7/
# UPDATE 2015-07-28
To fix the problem you mentioned in your comment, use the group option.
The group option: is a CSS selector indicates the parent element of field. By default, it is .form-group.
In your case, the parent of firstname and lastname is the div that have the class .col-sm-2, see the following code:
$(document).ready(function () {
$('#enableForm')
.bootstrapValidator({
feedbackIcons: {
// ...
},
fields: {
firstname: {
selector: '#firstName',
group: '.col-sm-2', // <===== USE THIS OPTION
validators: {
notEmpty: {
message: 'The first name is required and cannot be empty'
}
}
},
lastname: {
selector: '#lastName',
group: '.col-sm-2', // <===== USE THIS OPTION
validators: {
notEmpty: {
message: 'The last name is required and cannot be empty'
}
}
},
birthdate: {
// ...
}
},
onSuccess: function (e) {
// ...
}
});
});
See updated fiddle: http://jsfiddle.net/Arkni/kxxua2f7/2/

form validation and submission

I am using formvalidation.io but I cannot stop the form submitting on successful validation. It immediately submits request and refreshes page. I need to send form information via ajax.
I must be overlooking something obvious?
http://jsfiddle.net/k281at67/94/
The HTML:
<form method="post" id="estimateForm1" class="form-horizontal bv-form">
<input type="hidden" name="page_source" id="page_source" value=""/>
<fieldset>
<input type="hidden" name="RefferingPage" value="' . $page . '" />
<div class="form-group">
<div class="row">
<div class="col-md-8 pad_right">
<input type="text" class="form-control" name="Name" placeholder="*Your name" value="" />
</div>
</div><!--row-->
</div><!--form group-->
<div class="form-group">
<div class="row">
<div class="col-md-8 pad_right">
<input type="text" class="form-control" name="Phone" placeholder="*Phone" class="phone" value="111-111-1111" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-8 pad_right">
<input type="text" name="Email" class="form-control" placeholder="*Email" id="" value="pie#aol.com"/>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-2 col-md-offset-5 col-xs-2">
<button class="btn btn-default" type="submit" disabled="disabled">
<i class="fa fa-eye"></i>
Validate
</button>
</div>
</div>
</div>
</fieldset>
</form>
The Javascript
jQuery('#estimateForm1')
.formValidation({
framework: 'bootstrap',
err: {
container: 'tooltip'
},
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
Name: {
row: '.col-md-8',
validators: {
notEmpty: {
message: 'The first name is required'
},
stringLength: {
min: 2,
message: 'Must be at-least 2 characters long.'
},
regexp:
{
message: 'Please only use A-Z characters.',
regexp: /^[a-zA-Z]+$/
}
}
},
Phone: {
row: '.col-md-8',
validators: {
notEmpty: {
message: 'The phone number is required'
},
stringLength: {
min: 14,
max: 15,
message: 'Not a valid phone #.'
},
regexp: {
message: 'The phone number can only contain the digits, spaces, -, (, ), + and .',
regexp: /^[0-9\s\-()+\.]+$/
}
}
},
Email: {
row: '.col-md-8',
validators: {
notEmpty: {
message: 'The email address is required'
},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'The value is not a valid email address'
}
}
}
}
}).find('[name="Phone"]').mask('(000) 000-0000')
.on('success.field.fv', function(e, data) {
if (data.fv.getSubmitButton()) {
e.preventDefault();
//data.fv.disableSubmitButtons(true);
console.log('prevented submission');
}
}).on('success.form.bv',function(e)
{
e.preventDefault();
console.log('prevented submission');
});
You have a typo in your code:
This =>
.on("success.form.bv", function(e) { ...
should be =>
.on("success.form.fv", function(e) { ...
You have to trigger the event on the form instance, not the Phone field.
I suggest you to do the following:
jQuery('#estimateForm1')
.find('[name="Phone"]')
.mask('(000) 000-0000')
.end() // <=== DON'T FORGOT TO ADD THIS
.formValidation({
// ...
})
.on('success.field.fv', function(e, data) {
// ...
})
.on('success.form.fv',function(e) {
e.preventDefault();
console.log('prevented submission');
});
See Using Ajax to submit the form example.
Try this
.on('success.form.bv',function(e)
{
e.preventDefault();
return false;
console.log('prevented submission');
});
This function to stop call submit event. It should be calling manual
$(document).ready(function() {
$("#formname").submit(function(e) {
e.preventDefault();
});
});
Second option should be good for validation of form to client side. If you validate all value to return true then fire submit event other wise not fire.
function validation() {
return false;
});
But calling function on submit button like this
onclick="return validation()

I get jQuery error while submitting my bootstrap form

I have a small registration form and I try to submit this form using submitHandler of bootstrap but it gave me a Uncaught TypeError: Cannot read property 'attr' of null.
I use this code to validate and submit :
$(document).ready(function(){
//To validate the registration form and save its value after validation
$('#registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
notEmpty: {
message: 'The email is required and cannot be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
}
}
},
submitHandler: function(form) { // <- only fires when form is valid
$.ajax({
type: 'POST',
url: 'include-ajax/check_and_save_registration_form.php',
data: $(form).serialize(),
success: function() {
$(form).fadeOut(500, function(){
$(form).html("USER DONE!").fadeIn();
});
}
}); // <- end '.ajax()'
return false; // <- block default form action
}
}
});
});
Why do I get that error ? When I remove the submitHandler I do not get that error but I need it to store form data in my database.
The data validated correctly but not submitted.
I used also submitHandler: function(validator, form, submitButton).
Still giving the same error.
How to submit the form without getting error?
my for html :
<div class="pages_container">
<form id="registerForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-6">
<input class="form-control" name="email" type="email" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-6">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Retype password</label>
<div class="col-lg-6">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
<div class="form-group">
<div class="col-lg-6 col-lg-offset-3">
<button type="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</div>
</div>
</div>
</form>
</div>
Please see this page for the proper way to submit a form via ajax: Using Ajax to Submit the Form
$(document).ready(function() {
$(form)
.bootstrapValidator({
... options ...
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
}, 'json');
});
});

Categories

Resources