I am having strange problem.
My submit button only works if I reedit any field.
If i press submit button becoming disable.
Then i need to reedit date field (any field require validation) then I can submit the form.
Note:Even reediting any field,didn't work on jsfiddle(submit button still disable).But reediting works on my project!
Here is my code
Jsfiidle Link
$(document).ready(function() {
$('#reportForm')
.bootstrapValidator({
// Only disabled elements are excluded
// The invisible elements belonging to inactive tabs must be validated
excluded: [':disabled'],
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
reportStartDate: {
validators: {
notEmpty: {
message: 'Please select Date'
}
}
},
reportEndDate: {
validators: {
notEmpty: {
message: 'Please select Date'
}
}
}
}
})
// Called when a field is invalid
.on('error.field.bv', function(e, data) {
// data.element --> The field element
var $tabPane = data.element.parents('.tab-pane'),
tabId = $tabPane.attr('id');
$('a[href="#' + tabId + '"][data-toggle="tab"]')
.parent()
.find('i')
.removeClass('fa-check')
.addClass('fa-times');
})
// Called when a field is valid
.on('success.field.bv', function(e, data) {
// data.bv --> The BootstrapValidator instance
// data.element --> The field element
var $tabPane = data.element.parents('.tab-pane'),
tabId = $tabPane.attr('id'),
$icon = $('a[href="#' + tabId + '"][data-toggle="tab"]')
.parent()
.find('i')
.removeClass('fa-check fa-times');
// Check if the submit button is clicked
if (data.bv.getSubmitButton()) {
// Check if all fields in tab are valid
var isValidTab = data.bv.isValidContainer($tabPane);
$icon.addClass(isValidTab ? 'fa-check' : 'fa-times');
}
});
});
After spending half of my day finally found solution.The problem was 'name' attribute for button.Bootstrap validation having problem to understand form submitted or not!
When I use following way doesn't work!
<button type="submit" class="btn btn-warning" name="submit" value="showReport">Show Report</button>
With php code
if (isset($_POST['submit']))
Solution!
<button type="submit" class="btn btn-warning">Show Report</button>
With php code
($_SERVER['REQUEST_METHOD'] == 'POST')
I had the same problem but realised that I had targetted the container div and not the form-tag. Might save someone some time.
Related
I tried validation on HTML element which get printed via PHP but it is not working, but it does work when I put the same HTML without PHP.
Below is the HTML in which the actual data will be printed via AJAX:
<div class="row" id="live_data">
// here will all radio buttons and images echo via ajax
</div>
Here is the AJAX:
function fetch_all() {
var form_name = 'package_form2';
$.post('ajax/ajax_form_get_all_packages.php',{form_name:form_name}, function(result) {
console.log(result);
$('#live_data').html(result);
});
} fetch_all();
Here is the actual data which gets echoed via Ajax:
$output .= '
<div class="col-md-4">
<label for="'.$id.'">
<img src="uploads/'.$img.'" class="img-responsive">
</label>
<div>
<div class="radio text-center">
<input type="radio" id="'.$id.'" value="'.$code.'" name="optradio" class="optradio">
</div>
</div>
</div>
';
Here is the code of FormValidation:
$(document).ready(function() {
$('#menu1_info').formValidation({
message: 'This value is not valid',
icon: {
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
optradio: {
validators: {
notEmpty: {
message: 'Please choose one of the Package'
}
}
}
}
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var fv = $form.data('formValidator');
$form.bootstrapValidator('disableSubmitButtons', false);
});
});
There is no element with class optradio in your markup. Instead there is one with attribute name equal to optradio:
$(document).on('change', '[name="optradio"]', function() {
alert("Radio button clicked");
});
UPDATE
If I understood correctly, #menu1_info element comes from the ajax response
$(document).ready(function() {
$('#menu1_info').formValidation({
Here you are trying to select an element on document ready, but this element is not present to the DOM yet because it is appended asynchronously (after document ready event).
So, you have to initialize your plugin after the target element is present to the DOM (in the ajax callback function).
// The $('#menu1_info') element is not present now
$.ajax({
url: '...',
...,
success: function(data) {
// Append data from ajax call
$('#target').append(data);
// Now, $('#menu1_info') element is present
$('#menu1_info').formValidation({ ... });
}
});
There is no such element in the response '.optradio'.
Better to change to this:
$('#live_data').on('change', ':radio', function() {
alert("Radio button clicked");
});
Also you can delegate to closest static parent which in your case is #live_data
Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example
I want to display one error message at the top, if validation fails. I don't want to use errorPlacement option. Instead I want to show the message in the Bootstrap alert.
Here is my HTML:
<form method="POST" action="/role" accept-charset="UTF-8" id="roles_form">
<div class="alert alert-danger vd_hidden">
<span class="vd_alert-icon"><i class="fa fa-exclamation-circle vd_red"></i></span>
Please select a role.
</div>
<input id="role_administrator" name="role" type="radio" value="administrator">
<label for="role_administrator">Administrator</label>
<input id="role_manager" name="role" type="radio" value="manager">
<label for="role_manager">Manager</label>
<input type="submit" value="Submit">
</form>
Here is my JavScript:
var roles_form = $('#roles_form');
var error_roles_form = $('.alert-danger', roles_form);
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
debug: true,
rules: {
role: "required"
},
invalidHandler: function (event, validator) { //display error alert on form submit
error_roles_form.fadeIn(500);
},
});
This does not work. Neither it does any validation (form gets submitted, if I remove the debug option) nor does it show any error.
Update:
After looking at the solution provided by Sparky, I realised that I am using a plugin to hide radio elements and replace with a style-able object. As the radio elements were hidden, jQuery Validation failed to validate them properly with my JavaScript code. What surprised me is that it did not show any JavaScript error, even with debug mode on.
Quote OP:
"This does not work. Neither does any validation (form gets submitted, if I remove the debug option) nor [does] it shows any error."
Actually, the code you posted is working: http://jsfiddle.net/TTJB7/
Quote OP:
"I want to display one error message at the top, if validation fails. I don't want to use errorPlacement option."
For placing the error message into a box, you'll need the errorLabelContainer option. So instead of the default behavior of putting error messages next to each input (errorPlacement), the errorLabelContainer will put the messages into one specified container that is hidden/shown automatically.
var roles_form = $('#roles_form');
var error_roles_form = $('.alert-danger', roles_form);
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
debug: true,
rules: {
role: "required"
},
messages: {
role: "Please select a role."
},
errorLabelContainer: error_roles_form // puts the error messages into this container
});
HTML:
<form id="roles_form">
<div class="alert alert-danger vd_hidden"></div>
<input id="role_administrator" name="role" type="radio" value="administrator" />
<input id="role_manager" name="role" type="radio" value="manager" />
<input type="submit" value="Submit" />
</form>
DEMO: http://jsfiddle.net/TTJB7/1/
For all other available callback options, see the documentation.
When I realised that the actual problem is with the hidden radio elements, I did a little research and solved the issue.
First I applied ignore to "" so that it will not ignore hidden elements and validate them.
Then I need to stop default error message to appear after the element. So I assigned an empty function to that option.
Here is my final JavaScript code:
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
role: "required"
},
invalidHandler: function (event, validator) { //display error alert on form submit
error_roles_form.fadeIn(500);
},
errorPlacement: function(error, element) {}
});
I'm using jQuery Ketch-up plugin to validate my forms.
I need to validate a drop down box, Eg: if user select the drop down option 'select' it should fire the error saying 'Please select the language'.
Validate an email field but that email field is not a required one.
I tried to validate drop-down box using the following code as per the doc. but it says 'jq.ketchup is undefined'
//Drop down validation
var jq = $.noConflict();
jq.ketchup.validation('validateSelect', 'Please select the language', function(form, el, value)
{
if(this.contains(value.toLowerCase(), 'select'))
{
return false;
}
else
{
return true;
}
});
For my 2nd question there is no help on the doc.
jquery-ketchup plugin works properly for text and textarea inputs. To apply validation on select, use id of select input
Example:
select input:
html code:
= f.input :type, :prompt => "Select type", :collection => (some_collection), input_html: { id: "list_select" }
js code:
$.ketchup.validation('lselect', 'You have not selected type!', function(form, el, value) {
return value.length == 0 ? false : true
});
$("#form_id").ketchup({},{
'#list_select' : 'lselect'
});
To Validate email only if user entered any value, but not as required field, you need to override the validation provided by plugin as follows:
$.ketchup.validation('email', 'Must be a valid E-Mail.', function(form, el, value) {
return ($.trim(value).length > 0) ? this.isEmail(value) : true
});
I'm trying to use the JQuery validator on a form and am trying to figure out to get the messages of the errors in the invalidHandler option (or if there's somewhere else, do tell).
When a user clicks the submit button, whatever the first error is, I want to display an alert box with the message of the error. I don't want the error to be written on the document. I can't seem to figure out how to get the error messages to use in an alert after validation. I only found how to get the elements, and that doesn't really help me.
Pulling out from the example, here's some code I'm testing with
$(document).ready(function() {
$('#commentForm').validate({
invalidHandler: function(f, v) {
var errors = v.numberOfInvalids();
if (errors) {
var invalidElements = v.invalidElements();
alert(invalidElements[0]);
}
}
});
});
and
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
This works for me...
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Please correct the following error:\n'
: 'Please correct the following ' + errors + ' errors.\n';
var errors = "";
if (validator.errorList.length > 0) {
for (x=0;x<validator.errorList.length;x++) {
errors += "\n\u25CF " + validator.errorList[x].message;
}
}
alert(message + errors);
}
validator.focusInvalid();
}
I know the question is quite old, but to help other people to get a better answer I would advise you guys not using invalidHandler, but showErrors.
Thats because invalidHandler will be called only when you submit your form while
showErrors is called every time a field is updated.
So, do this:
Script in the end of the page
$("form").validate({
rules: {
name: {
required: true
}
},
messages: {
name: {
required: "required"
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error')
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Your form has 1 error'
: 'Your form has ' + errors + ' errors.';
message = message + ' Please, fix then.'
$("#error span").empty().html(message);
$("#error").show();
} else {
$("#error").hide();
}
this.defaultShowErrors();
},
});
Don't forget your html tag
<div id="error"><span></span></div>
Overloading showErrors worked as expected. I just needed to get the first error message.
showErrors: function(errorMap, errorList) {
alert(errorList[0].message);
}
Also remember to take a look at the onfocusout and onkeyup options, else you'll get continuous messages.
MUST check errorList.length
if (errorList.length > 0) alert(errorList[0].message);
You should not use alert,
But if you really want to use that. Solution depend of how plugin add dom elements but you can remove those dom elements in invalidHandler. So let those dom element added but remove it.
Other option is, you should patch plugin you use for validation and instead of adding dom show alert.