I am using this Bootstrap validator github.com/1000hz/bootstrap-validator for my bootstrap forms but it appears there is no way to set some external JS conditional before submitting forms.
For example, I would like to do the following from an external JS files:
1 # if form or some input of the form is invalid using validator() then I do some action.
2 # else Users will see some bootstrap button loading message until everything is submitted into the databases.
You can have a single case here:
$('button[data-loading-text]').click(function () {
var btn = $(this);
btn.button('loading');
$.blockUI();
// #1 if form is invalid using validator() then I unblock the please wait message $.unblockUI(); and reset the bootstrap loading button.
// #2 else users will still see the "please wait" message + bootsrap loading button untill everything is submitted into the databases.
});
http://jsfiddle.net/temgo/k07nx06k/12/
Any help will be appreciated as it appears the plugin events are only set for specific field not for full form validation.
Regards
Check out the Events section on 1000hz page. (http://1000hz.github.io/bootstrap-validator/#validator-events)
If you want to fire up the action before validating - just listen to the event.
$('#someFormId').on('validate.bs.validator', function(){
doSomeStuff();
});
Edit
The problem with events is that it is fired after every field. From what I know this plugin doesn't provide an event for finished successful validation.
For your ref hope it will help u
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('Done');
}
});
});
I came across this question looking for something else, but I have worked on precisely what you're trying to achieve.
My solution was to use the snippet of code the plugin author gives for binding to the submit button
$('#form').validator().on('submit', function (e) {
if ( !e.isDefaultPrevented() ) {
// put your conditional handling here. return true if you want to submit
// return false if you do not want the form to submit
}
});
Hope that helps someone out.
$(function () {
$("#myForm").validator();
$("#myButton").click(function (e) {
var validator = $("#myForm").data("bs.validator");
validator.validate();
if (!validator.hasErrors())
{
$("myForm").submit();
} else
{
...
}
}
})
Hope with will help.
I am working so much for a better coding with this form validator js plugin.
Follow my code and try yourself:
// Select every button with type submit under a form with data-toggle validator
$('form[data-toggle="validator"] button[type="submit"]').click(function(e) {
// Select the form that has this button
var form = $(this).closest('form');
// Verify if the form is validated
if (!form.data("bs.validator").validate().hasErrors()) {
e.preventDefault();
// Here go the trick! Fire a custom event to the form
form.trigger('submitted');
} else {
console.log('Form still not valid');
}
});
// And in your separated script, do the following:
$('#contactForm').on('submitted', function() {
// do anything here...
})
Consider the following HTML code:
<form id="contactForm" action="/contact/send" method="POST" data-toggle="validator" role="form">
<div class="form-group has-feedback">
<label for="inputName" class="control-label">Name:</label>
<input type="text" name="inputName" id="inputName" class="form-control" data-error="Your input has an invalid value"/>
<span class="help-block with-errors"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Send</button>
</div>
</form>
you can use validated.bs.validator to hand the event in order to do something after validating the form.
Regards!
Related
I have a two text fields and one submit button in my application. When I click the submit button if any one of the text field is empty it should tell me 'Please fill out the field'. So I used bootstrap 'needs-validation' in my script. Now when I click the submit it is not going inside the if or else loop of the validation. If the condition is true it should go inside the else loop and should do the ajax call.If the ajax call is success it should send the alert message to the user. But I dont see the alert message and POST call is also not happening.
My HTML script is
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
console.log("I am inside function");
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
console.log("I am inside submit")
if (form.checkValidity() === False) {
console.log("I am inside true");
event.preventDefault();
event.stopPropagation();
}
else {
console.log("I am inside else");
var departments = $("#role").val();
var facultyList = $("#faculty").val().split(',');
facultyList.pop();
console.log(facultyList);
$.ajax({
type: 'POST',
url: '/departments/add',
data: {
'role': departments,
'facultylist': JSON.stringify(facultyList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
}
form.classList.add('was-validated');
}, false);
});
}, false);
}) ();
<div class="row top-space-30">
<form class="needs-validation">
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="deprole">Department :</label>
<div class="col-md-6">
<input id="role" name="deprole" type="text" placeholder="QA" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="faculty">Faculties:</label>
<div class="col-md-8">
<input class="form-control" type="text" id="faculty" required>
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="submit" id="submit">Submit</button>
</div>
</form>
</div>
When I run the script I can see in the console log 'I am inside submit'. But When I click the submit button without entering the details I dont see 'I am inside true' in the console log. But validation will happen. When I enter the details in two fields and click the submit button I dont see 'I am inside else' in the console log and I dont see the alert function in my application also
What I need is:
-When I click the submit button with details I should see the ajax call and should see the alert message.
There are a few problems..
The JS boolean value should be false not False
The preventDefault() and stopPropagation() should be called regardless of validation
since you want to stop the default behavior of the submit button
Demo: https://codeply.com/p/wtSkr8Eucc
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
event.stopPropagation();
if (form.checkValidity() === false) {
console.log("I am inside true");
}
else {
console.log("I am inside else");
var departments = $("#role").val();
var facultyList = $("#faculty").val().split(',');
facultyList.pop();
console.log(facultyList);
$.ajax({
type: 'POST',
url: '..',
body: {
'role': departments,
'facultylist': JSON.stringify(facultyList)
},
success: function (result) {
alert("The department has been added");
}
})
}
form.classList.add('was-validated');
}, false);
});
When you click on the 'Submit' button, your form makes a default action, which is sending the form data (in a form of GET attribute) to the same page that holds the form (normally those can be controlled by the 'action' and 'method' attributes of form tag).
That in effect means that the page 'reloads' itself before executing any JS code.
To prevent that default action, add event.preventDefault(); in your event listener code block and it should be fine.
form.addEventListener('submit', function (event) {
event.preventDefault();
console.log("I am inside submit")
Also important, don't rely on browser validation, which can be easily avoided. Make sure to implement a back-end validation / sanitation function as well.
I'm having trouble adding an event on a button that submits the form and after submission stopping the page redirect. I found other answers where I tried adding return false and preventDefault but neither are working.
Why is this not working?
function submitform() {
document.getElementById("form").submit( function () {
return false;
});
}
I added the click event to the button
<button id="button" onclick="submitform();">Submit Form</button
Here is an example that shows the javascript not working.
You are calling the function that is then listening for the form being submitted when there are no further events. Basically you are listening for an event that never comes.
There is no need to call the function on the submit in your supplied fiddle as the event is happening on the button.
I added a quick empty test for the email address just to show the process.
Amended Pen: https://codepen.io/anon/pen/dRRbyw
HTML
<button id="button" onclick="submitform();">Submit Form</button>
<br /><br />
<form id="form" method="post" action="https://submit.jotform.us/submit/71714528616156/">
Email
<input type="text" name="EMAIL" id="EMAIL" label="Email" value="">
JS
function submitform() {
if(document.getElementById("EMAIL").value == "") {
alert('nope');
return false;
} else {
alert('yep');
document.getElementById("form").submit();
}
}
Let me know if you need any more explanation.
you can use ajax to handle the form submission without redirecting the page. You will need to be using jquery for this solution:
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
data: { EMAIL: $(this).name.value }
});
return false;
});
})
incredibly similar question/answer here: Prevent redirect after form is submitted
Have this problem that form inputs with assigned mask (as a placeholder) are not validated as empty by jQuery validation.
I use:
https://github.com/RobinHerbots/jquery.inputmask
https://github.com/1000hz/bootstrap-validator
(which uses jQuery native validation in this case)
Some strange behaviors:
Inputs with attribute required are validated (by jQuery) as not empty and therefore valid, but in the other hand input is not considered as "not empty" and not checked for other validation rules (this is by validator.js)
When i write something into input field and then erase it, I get required error message
Can anyone give me some hint?
EDIT:
Relevant code:
HTML/PHP:
<form enctype="multipart/form-data" method="post" id="feedback">
<div class="kontakt-form-row form-group">
<div class="kontakt-form">
<label for="phone" class="element">
phone<span class="required">*</span>
</label>
</div>
<div class="kontakt-form">
<div class="element">
<input id="phone" name="phone" ' . (isset($user['phone']) ? 'value="' . $user['phone'] . '"' : '') . ' type="text" maxlength="20" class="form-control" required="required" data-remote="/validator.php">
</div>
</div>
<div class="help-block with-errors"></div>
</div>
</form>
JS:
$(document).ready(function() {
$('#phone').inputmask("+48 999 999 999");
$('#feedback').validator();
});
I managed to use the RobinHerbots's Inputmask (3.3.11), with jQuery Validate, by activating clearIncomplete. See Input mask documentation dedicated section:
Clear the incomplete input on blur
$(document).ready(function(){
$("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
});
Personnaly, when possible, I prefer setting this by HTML data attribute:
data-inputmask-clearincomplete="true"
The drawback is: partial input is erased when focus is lost, but I can live with that. So maybe you too ...
Edit: if you need to add the mask validation to the rest of your jQuery Validate process, you can simulate a jQuery Validate error by doing the following:
// Get jQuery Validate validator currently attached
var validator = $form.data('validator');
// Get inputs violating masks
var $maskedInputList
= $(':input[data-inputmask-mask]:not([data-inputmask-mask=""])');
var $incompleteMaskedInputList
= $maskedInputList.filter(function() {
return !$(this).inputmask("isComplete");
});
if ($incompleteMaskedInputList.length > 0)
{
var errors = {};
$incompleteMaskedInputList.each(function () {
var $input = $(this);
var inputName = $input.prop('name');
errors[inputName]
= localize('IncompleteMaskedInput_Message');
});
// Display each mask violation error as jQuery Validate error
validator.showErrors(errors);
// Cancel submit if any such error
isAllInputmaskValid = false;
}
// jQuery Validate validation
var isAllInputValid = validator.form();
// Cancel submit if any of the two validation process fails
if (!isAllInputValid ||
!isAllInputmaskValid) {
return;
}
// Form submit
$form.submit();
It's not exactly the solution, but...
changing inputmask for some equivalent solves the problem.
Still far from perfect, though : (
EXPLANATION:
Other masking libraries, don't have these two strange behaviors mentioned, so it's possible to validate fields.
I used:
https://github.com/digitalBush/jquery.maskedinput
I have the same issue when combined these two libs together.
Actually there is a similar ticket here: https://github.com/RobinHerbots/Inputmask/issues/1034
Here is the solution provided by RobinHerbots:
$("#inputPhone").inputmask("999.999.9999", {showMaskOnFocus: false, showMaskOnHover: false});
The validator assumes that it is not empty when the mask focus/hover is there.
simply turn focus and hover of the mask off will fix the problem.
I solved this problem with:
phone_number: {
presence: {message: '^ Prosimy o podanie numeru telefonu'},
format: {
pattern: '(\\(?(\\+|00)?48\\)?)?[ -]?\\d{3}[ -]?\\d{3}[ -]?\\d{3}',
message: function (value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^ Nieprawidłowa wartość w polu Telefon");
}
},
length: {
minimum: 15,
message: '^ Prosimy o podanie numeru telefonu'
},
},
Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.
Ні, all!
I have a little question about jQuery.Validation plugin: - Can I complete validation for input fields that are not form fields (i.e no in the "form" tag) using jQuery.Validation plugin?
Thanks.
Yes you can, but the field still needs to be inside a set of <form> tags. However, you do not need to "submit" this form in order to check validation on the field(s) inside. You use the .valid() method to check this form independently of form submission.
http://jsfiddle.net/9fgVN/13/
<form id="myNonsubmitForm" action="#">
<textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>
<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />
$(document).ready(function() {
$("#myNonsubmitForm").validate({
validClass: 'valid', // as per your configuration
rules: { // set rules as per your configuration
comments: {
required: false,
maxlength: 10
}
},
errorPlacement: function(error, element) {
// use this to control placement of error messages
// removal of errorPlacement handler will result in message appearing next to field automatically.
}
});
$("#myButton").click(function() { // validate on button click for this example
if($("#myNonsubmitForm").valid()){
$('#output').val('passed');
} else {
$('#output').val('failed');
};
});
});