1000hz / bootstrap-validator Goto Github PK
View Code? Open in Web Editor NEWA user-friendly HTML5 form validation jQuery plugin for Bootstrap 3
Home Page: http://1000hz.github.io/bootstrap-validator
License: MIT License
A user-friendly HTML5 form validation jQuery plugin for Bootstrap 3
Home Page: http://1000hz.github.io/bootstrap-validator
License: MIT License
I am trying to fire some stuff when a determined field got errors. So I have tried the Events as said here: http://1000hz.github.io/bootstrap-validator/#validator-events
Pretty much like this:
$('#new_user').on('invalid.bs.validator', function () {
console.log('invalid input!');
});
But actually nothing happens, what am I doing wrong?
Thank you.
Edit: '#new_user' is my form element.
I think it would be nice if you could for Ajax loaded forms. It becomes messy at times when you dynamically load a form on the webpage using PHP, Ajax , Jquery . If you could embed .ajaxStop()
and listen for dynamically loaded forms it will be great.
Custom functions for add and remove error on an input field. This will enable developers to add their own validations if necessary
eg:
if( !valid() ) { displayError('Some error message'); } else { removeError(); }
Right now the plugin uses HTML5's element.checkValidity() to support all of the standard HTML5 Form validation types. This means they won't work in older browsers.
The plugin should implement all of its own validators to ensure cross-browser support.
Hi I'm trying to instantly display a modal 'loading' box when the submit button is pressed on a form. I've achieved this by doing the following:
$('form').on('submit', function (event) {
showLoadingModal();
if (!event.isDefaultPrevented()) {
event.preventDefault();
submitForm(this);
} else {
hideLoadingModal();
}
});
However I'm getting a problem where there is a small gap of time (under a second) between clicking the button and the modal being displayed. I'm assuming this delay is caused by the time taken validating all the fields on the form of which there are quite a lot.
This therefore leads me to believe that the validator 'form submit' is being executed before my code and I should be doing something different to call the showLoadingModal()
I add this code
jQuery.validator.addMethod("orgNotExist", function(value) {
var in_array = $.inArray(value.toUpperCase(), orgNames);
if (in_array == -1) {
return true;
}else{
return false;
}
}, "This organization url exists before");
$("#confirmForm1").validate();
but the error appears in blue color, but I want to use red one like your plugin, How can I do that ? ..
can I use custom validator using your plugin ?
hi
when validating a form with the jquery-ui (combobox) plugin.
http://jqueryui.com/autocomplete/#combobox
while validating... all select lists pop open.
example:
http://jsfiddle.net/tLcqs0ak/1/
thanks allot
Avi
I assumed I could do the following (the enabled validator is a custom validator, it works)..
var bv = {
message: {
notEmpty: {
message: 'The street name is required and can\'t be empty.'
}
},
validators:{
enable_only: {
enabled: {
valid: true
}
},
options: {
enabled: {
valid: true
},
date: {
format: 'DD/MM/YYYY',
message: 'The value is not a valid date. The format of the date is DD/MM/YYYY'
}
}
},
fields: {
trn: {
validators: {
regexp: {
regexp: /\d{9}/,
message: 'This is not a trn number, \n trn must be nine (9) digits'
}
}
},
address:{
location: {
helpMessage: 'Give the name of the Building/Complex/Apt./Suite/lot # and housing development.',
validators: {
enabled: {
valid: true
}
}
},
street_num: {
validators: {
enabled: {
valid: true
}
}
},
street_name: {
validators: {
notEmpty: {
message: 'The street name is required and can\'t be empty.'
},
}
},
town_district: {
validators: {
notEmpty: {
message: 'The town/district is required and can\'t be empty.'
},
}
},
post_box: {
validators: {
digits: {
message: 'PO box can contain digits only.'
}
}
},
post_office: {
validators: {
enabled: {
valid: true
}
}
}
}
}
};
In a libs file and then have this in another file...
$("form[name='address_info']").bootstrapValidator({
field: bv.fields.address
});
Any thoughts?
Hey thanks for the nice lib.
I am having some trouble with the pattern matching. It might be just my stupidity but it doesn't seem to behave as expected. Got any ideas?
I am trying to match a mobile phone number with a country code prefix.
Basicaaly I want +2222222222 to validate and 2222222222 not fail aswell as any occurence of a non-digit except for the plus at the front. But spaces are cool.
my pattern is /^[\+][\d\s]+$/
my html is
<input id="mobile-number" type="tel" name="user[mobile]" placeholder="#### ####" pattern="/^[+][ds]+$/" data-minlength="8" data-maxlength="20" required="" autocorrect="off" spellcheck="false" autocapitalize="off" class="form-control">
and when I enter a value of +1111111
I get a "Please match the requested format."
However when id the following in the terminal, I get a match
text = $('#mobile-number').val()
text.match(/^[\+][\d\s]+$/)
So am I stupid?
Hello,
I tried using the validator to validate the inputs for a form that is submitted with a submit-button outside of the form or via pressing the enter key (prevented default behaviour and calling of a customary function).
But from what little documantary is given with the example, I'm not able to find out how to do something like
if (form not valid) {
do nothing
} else {
call custom function
}
Calling validator('validate') on the form as is said in the documentation isn't blocking/doesn't keep the function from executing the next line. I've found the "isIncomplete" and "hasErrors" functions in the .js file, but can't seem to figure out how to use them.
A bit more documentation on how to use the validator would be greatly appreciated.
It would be nice to have an ajax validator that sends a request to an endpoint and returns either a success or error response, which gets shown to the user.
Like if you needed to check whether a username was available or something.
Hi,
I've checked input of email type or with pattern, it works OK. But the validator doesn't catch error with input type="number" when I enter something other then number (with min, max attributes or without).
How do you change language on error messages?
From where are they fetched?
FYI,
Added a validation message for pattern, dont know if it's best approach.
if (key == 'native' && typeof $el.attr('pattern') !== typeof undefined)
key = 'pattern';
Now i can run
$('form').validator({
delay: 500,
html: false,
errors: {
pattern: "Not valid pattern",
match: 'Dont match',
minlength: 'lalalala'
}
});
At least this method can be applied to more attributes...
Wait for feedback.
When I go to a browser autocomplete form and it's valid, the submit bottom is "disabled". When I clic the "body" or change the field focus it turn enabled, but is disabled in the "first view".
bootrapValidation v3.1 worked fine validating CHOSEN drop downs. I initialized the JS file as follows:
//* Chosen Configuration & Initialization
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'No restults found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
I recently installed the iCheck plugin, which has nothing to do with CHOSEN as far as I can tell, and was having issues getting the checkboxes to validate. I upgraded my bootstrapValidation to v4.2 and initialized iCheck as follows:
//* iCheck iRadio initialization
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
focusClass: 'focus',
increaseArea: '20%'
});
$('input').on('ifChecked', function(event){
$('input').iCheck('update');
});
I had to add the following JS to revalidate the checkboxes when needed:
//* Update validator if iCheck field changes
$('input').on('ifChanged', function(event){
var formId = this.form.id; //Get the ID attribute of the closest (current) form
var elementName = $( this ).attr("name");
$( '#'+formId )
// Get the bootstrapValidator instance
.data('bootstrapValidator')
// Mark the field as not validated, so it'll be re-validated when the user change date
.updateStatus( elementName, 'NOT_VALIDATED', null)
// Validate the field
.validateField( elementName );
});
This all worked great for iCheck and validated nicely. However, when I upgraded to boostrapValidation v4.2 my CHOSEN fields no longer would validate. I believe it is related to large amount of changes from bootstrapValidation v3.2 to v4.2. The only other change was adding iCheck plugin. That is why I mentioned that as well.
I need some help in validating CHOSEN fields in bootstrapValidation v4.2.
Here's a snippet of HTML5
JQuery snippet:
$('#inspection').bootstrapValidator({
message: 'This value is not valid',
//* live: 'enabled',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
structureAddress: {
message: 'The structure address is not valid',
validators: {
notEmpty: {
message: 'The structure address is required!'
}
}
},
structureLocation: {
validators: {
notEmpty: {
message: 'Structure Location is required'
}
}
},
structureCityZipCounty: {
validators: {
notEmpty: {
message: 'Structure city, zip and county are required!'
}
}
},
structCitylimit: {
validators: {
notEmpty: {
message: 'City limit selection is required!'
}
}
},
structCobra: {
validators: {
notEmpty: {
message: 'Structure cobra required! Yes / No'
}
}
}
}
});
Thank you :)
Are there any chance to add support for textarea regex validation?
html5 does not support pattern attribute in textarea element
but maybe, this plugin will be able to?
I have an inline form with ~3 input fields per row, each different. It seems that all the .help-block classes are found within the form-group, and they all display the same error message (e.g. when tabbing out of one, all 3 will display the same error message from that input). Is this something I could work around?
There have been a few issues (#30, #35) asking how to check if the form in invalid in order to prevent some function from running on submit. Since the submit
event gets .preventDefault()
called on it if the form isn't valid, the docs should call attention to the fact that you can check e.isDefaultPrevented()
to return early from a custom submit handler.
I notices this part
Validator.prototype.toggleSubmit = function () {
var $btn = this.$element.find('input[type="submit"], button[type="submit"]')
$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
.css({'pointer-events': 'all', 'cursor': 'pointer'})
}
With this the button gets the class "disabled", using it with bootstrap it prevents the button being clicked but the line.css({'pointer-events': 'all', 'cursor': 'pointer'}
adds style="pointer-events': 'all'"
allowing to click and sending a blank form; so this should be erased.
Any way to add this?
How to change default error message?
I tried this:
$('.page-form').validator(
errors: {
required: "Please enter a valid string..."
}
);
but won't work - still display default/translated message
It would seem more constructive for the user experience if the validation of email address happened after the user moved to another field or attempted to submit form. Perhaps a few second delay from the last input. The way it is now user is getting an error before they are completed with input.
example: from your demo if you enter in myname it will show error before you get a chance to put @. Perhaps a slight delay could avoid this?
I can't find the definition of the .width-errors class in sourece file.
is there a way to effect this validation on ie9?
It would be nice if help-block would be appended to parent element automatically so you don't have to put that many empty elements to the form.
Do you think it's possible?
We saw this with an email input that had a remote validation:
<input type="email" name="email" data-remote="/api/validate/user" data-remote-error="That email has already been taken">
If the user enters, '[email protected]', that API service will receive a GET request with:
/api/validate/[email protected]
but should be sending:
/api/validate/user?email=user%2B1%40example.com
To fix the issue, you could either call encodeURIComponent on the key and value prior to joining them with the equals sign, or build up an object and let jQuery do the encoding (the approach that I took in the pull request).
I am using AJAX to submit a form and the code below is always invalid before I submit the form (Failing) - right now I have an alert on the test page. Not sure why this is happening, only three fields are "required" - name, email, and phone (I only want to submit if the required fields are ok) but it fails even if all fields are filled. I also initialize the form after your js file loads.
Test site: http://tempuswebs.com/clients/itrsphp/contact.php
$(window).on('load', function () {
$('#contactForm').validator().on('submit', function(e) {
if(e.isDefaultPrevented()) {
alert("The form is not completed correctly");
} else {
var dataString = $('#contactForm').serialize();
$.ajax({
type: 'POST',
url: 'services/process-email.php',
data: dataString,
success: function(res) {
if (res == 'successful') {
window.location=('thanks.php');
}
else {
//alert("failed");
window.location=('thanks.php');
}
},
error: function () {
window.location=('thanks.php');
}
});
}
});
});
Can't put validation on select fields of form please help as soon as possible
Since radio buttons aren't treated as a group, selecting one will only clear the error for that single radio button and the form will remain invalid.
I found a few faults in Email Validation. When i type ' [email protected] ' it a valid email address but when i type ' asa@asda ' bootstrap-validator considers this as a valid email address.
Examples of invalid email addresses considered as valid by ' bootstrap-validator '
I'm not good with javascript but i hope this regex will help.
RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/)
Perhaps add compatibility notes to the readme/instructions?
The current version does not validate <textarea> fields.
Trying your plugin here: http://1000hz.github.io/bootstrap-validator/ if I don't enter any values at all and click submit, it doesn't show any errors (but refuses the submission as expected). I'd expect to show the error for every required field?
If I then click in name, and without typing anything click submit, it marks the name field as required, as expected, and doesn't submit, however, it doesn't highlight any other empty field. This seems to apply to any of the fields in the form.
It's as if you need to click into the input field before it will add the error class to that field when the form is submitted?
Hi Cina,
I have spent a lot of time to make this to work but I am not sure what I am doing wrong.
I made a simple fiddle to show you what I am doing.
Could you please have a look and advise me what I am doing wrong?
http://jsfiddle.net/zardaloop/eohauchg/
Cheers.
I want to use with jquery ajax. And I need a flag that indicates to current situation of validating form.
For instance;
if($('#myForm').Validate()) {
$.get(function() {
.............
}
}
Mind running a npm publish
thanks
I met a problem when i used this form validation widget.
var $btn = this.$element.find(':submit')
This code made my all button in the form to be disabled.
I change this code to:
var $btn = this.$element.find('[type="submit"]')
Do you think what i do is right.
Thank you.
I am from China, my english is not very good, so if you don't understand what i said, apologize for that
The sidebar links are always clickable even if a related panel has required fields and the NEXT button is disabled.
If a panel contains some required fields, when the panel is opened (either on first load or other panels toggled), the NEXT button is clickable. I think this should default to disabled if there is required form elements.
I have forms that have divs that are hidden or shown depending on checkbox options.
How can I skip validation for fields in hidden divs?
Thanks,
John
I use bootstrap-validator with angular-ui/bootstrap and get an exception: "Uncaught TypeError: Cannot read property 'length' of undefined". It appears if I open modal window and close it without any changes.
this.defer($el, function () {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var errors = $el.data('bs.validator.errors')
// Exception is thrown from this line:
if (!errors.length) return
// ...
}
Angular template:
<form id="postEditor" data-toggle="validator" role="form">
<div class="modal-header">
<h4 class="modal-title">Add new post</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input ng-model="entity.url" ng-disabled="sending"
id="url" type="url" class="form-control" placeholder="URL"
data-error="URL address is invalid" autofocus required/>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input ng-model="entity.tags" ng-disabled="sending"
id="tags" type="text" class="form-control" placeholder="Tags"
data-error="Enter at least one value" required/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-click="ok()" ng-disabled="sending">Post</button>
<button type="button" class="btn btn-default" ng-click="cancel()" ng-disabled="sending">Close</button>
</div>
</form>
Hi,
first thanks for this script, i'm trying to use it in my project and i'm stuck on it :
I have a form separated in 5 parts ( Twitter collapsed panels ) and in theses part, i have a Next button ( )
Thanks in advance for your help
My use case is that I've got to fields with a start and end date. I need to validate those to make sure the start date is not after the end date. How would I go about doing something like that?
(happy to do a fork/PL to make it happen)
โ Hi Guys, is the data-remote tag explained anywhere? I couldn't find it on the documentation, is there any example? I tried a couple of combinations but I can make it work. Thanks in advance!
I have a checkbox array of some elements, with "required" attribute, and the validator need all the checkboxes checked for pass the validation (when I just need at least one checked for my form). How can I define this?
Hello
I'm trying to use the option data-disable to disble the submit button if there is any error on the form.
However all of these tries didn't work:
Or if there is way to check if the form is validated during submit will help also
$('#NewUserForm').submit(function(e) {
}
Could you help me? Thank you
Hi.
For example form is in modal and you need to reset/reinit validation on modal show.
Plugin needs destroy method - .validator("destroy")
or smthing like this.
Hello!
First of all thank you for validator.js which is a very useful project.
I have a form to validate and for which I have implemented the method $('#myForm').submit() for processing the form. My issue is that this function is called, and so the data processing is performed, when I click on the Submit button even though the form has not been validated (e.g. a required field is left blank).
Which method can I call inside submit() to know whether the form has been validated (and then process the data) or not (and then leave without doing anything)?
Best,
Thomas
Tabbing through any required fields doesn't show an error. You have to type something in and then if you delete it works.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.