cferdinandi / bouncer Goto Github PK
View Code? Open in Web Editor NEWA lightweight form validation script that augments native HTML5 form validation elements and attributes.
License: MIT License
A lightweight form validation script that augments native HTML5 form validation elements and attributes.
License: MIT License
I have a long form, a really long in fact.
I'd like to validate it in parts, e.g. when custom button at the end of fieldset is clicked it validates that fieldset (I'm not using <fieldset>
element but a <section>
but the point is same).
Currently I'm doing it like this, which works just fine, but I have to re-implement some of the focus stuff:
var bouncer = new Bouncer("form", {
disableSubmit: true
});
form.find("button.next").click(function() {
var section = $(this).parent();
var isValid = true;
var jumpToError = function(event) {
window.scrollTo(0, event.target.offsetTop);
event.target.focus();
};
// Notice jQuery "one" callback hook
section.one("bouncerShowError", jumpToError);
section.find(":input").each(function() {
var result = bouncer.validate($(this).get(0));
if (result && !result.valid) {
isValid = false;
}
});
section.off("bouncerShowError", jumpToError);
if (!isValid) {
// Hide current section, show next section code snipped
}
});
Apologies for the jQuery in my example, but the point should be clear.
What I would like to have is a API such as:
var bouncer = new Bouncer("form", {
disableSubmit: true
});
bouncer.validate(document.querySelector("fieldset.first"));
Which would validate all fields in the fieldset, do all the necessary other stuff, not sure what that is.
This is not a very important feature, but I gather someone else could make use of it too.
When the inputs contain square brackets [ ] (ex: <input type="email" name="ContactForm[email]">
), it creates a duplicated error message each time the input is validated. In the code, field.form.querySelectorAll('[name="' + field.name + '"]')
wont' work because it will look for [name=ContactForm[email]]
and it doesn't like the double [ ].
Use a variant of this: https://github.com/cferdinandi/smooth-scroll/blob/master/src/js/smooth-scroll.js#L101-L179
When configuring custom error message, for constraint outOfRange or wrongLength,
if it's done via a function (instead of via plain string),
then it fails.
ex : cfg.messages.outOfRange.over = function (field) { ... return myMessage; }
/**
* Get the error message test
* @param {Node} field The field to get an error message for
* @param {Object} errors The errors on the field
* @param {Object} settings The plugin settings
* @return {:point_right:String|Function:point_left:} The error message
*/
var getErrorMessage = function (field, errors, settings) {
...
// Numbers that are out of range
if (errors.outOfRange) {
return messages.outOfRange[errors.outOfRange].:point_right:replace:point_left:('{max}', ...
Im attempting to validate some files prior to upload , i already have server side validations in place , this is more so the user doesnt have to painfully fail so far into the process .. anyways the code below is what i have ... and is live on this URL. : https://www.wiiubru.com/formvalid.html
`var bouncer = new Bouncer('[data-validate]', {
disableSubmit: true,
customValidations: {
isZIP: function (field) {
var file = document.forms['validate-me']['file'].files[0];
if (file && (file.type == "application/x-zip-compressed" || file.type == "application/zip")) {
return false;
}
return true;
},
maxfilesize: function (field) {
var maxfilesize = 20971520; // 20meg
var zipfile = document.forms['validate-me']['file'].files[0];
if (zipfile && zipfile.size < maxfilesize) {
return false;
}
return true;
},
screenisPNG : function (field) {
var screenfile = document.forms['validate-me']['screenToUpload'].files[0];
if (screenfile && (screenfile.type == "image/png" || screenfile.type == "image/x-png")) {
return false;
}
return true;
},
iconisPNG : function (field) {
var iconfile = document.forms['validate-me']['iconToUpload'].files[0];
if (iconfile && (iconfile.type == "image/png" || iconfile.type == "image/x-png")) {
return false;
}
return true;
},
iconValidsize : function(field) {
var imageisfine = 0;
var iconFile = document.forms['validate-me']['iconToUpload'].files[0];
if(iconFile) {
var img = new Image();
img.onload = function () {
if (this.width == 256 && this.height == 150) {
imageisfine = 1;
alert(imageisfine);
}
};
img.src = URL.createObjectURL(iconFile);
}
}
},
messages: {
isZIP: 'Please make sure the package is a zip file',
maxfilesize: 'Your Zip file is too large',
screenisPNG: 'Your image must be a valid PNG file',
iconisPNG: 'Your image must be a valid PNG file',
iconValidsize: 'Your icon image has incorrect dimensions'
}
});`
I seem to get multiple 'isZIP' messages displayed and also im stuggling to validate image dimensions. A trial on the live site may better explain the problem im having .. NOTE only need to bother with the Upload buttons at the bottm the rest is just simple form fill.
Hey,
This code here is problematic.
Why?
What if a field doesn't have a sibling?
I have just one field in a container and that's all and so because of that I get error because there is no sibling.
// If the message should come after the field
if (settings.messageAfterField) {
return target.nextSibling;
}
and than you use
field.parentNode.insertBefore(error, location);
and it should be like selecting insertBefore
or insertAfter
Best,
Tom
Hi there,
It would be really nice if you could add a custom error message as a data attribute to a field.
I would assume that data-bouncer-message
would do the trick but it only works when a pattern fails, as you can see from this fiddle:
https://jsfiddle.net/rsx83ouw/5/
Other than that, a great library!
Hey,
When having an email type filed on IE11 I get this error on keypress or submit:
SCRIPT5017: Syntax error in regular expression
bouncer.js (199,3)
Can I use bouncer to validate that an item other than the "select One" has been selected in select that is dynamically populated by clientside JavaScript? I didn't see any examples of bouncer validating selects.
Hi, not sure if right way to submit...
seems that the scroll to input with error doesn't take into account sticky header, i.e. if form is longer than viewport, and error field is above top of vp, the positioning is under sticky header.
I hope that make sense.
will try with position:fixed and see if the same.
many thanks
edit: 4 minutes later. Sorry checked code and see the error field has focus set. Not sure what you can do. Will have a think myself. Cheers
edit: 10 minutes later. If error focus was turn offable in options, could handle scrolling and focus in eventlistener on custom event?
The input element with type='submit' name='submitted' is not present in the array $_POST. Guess its because the validation on the submit-event. Is there any easy solution?
File field is not giving required error: <input name="file" type="file" required />
Test case: https://codepen.io/ciantic/pen/ebzJZr
With custom validation: How can i validate two field is equal?
For radio groups with messageAfterField
set to false
, grab first item in group instead of last for error field.
Potentially also use field instead of label.
hey @cferdinandi thanks for ur lightweight package 😍
can we have better documentation in demoLink ?
some usefull validation
1.Password strength
2. shorter than or bigger than 6 for example
another question is how to validate one input one by one
if valid addClass of success ( for example green border ) for 3 sec user find out input isValid
and how to use data-bouncer-message
for normal input like type="text"
Regards <3 👍
Source: https://editorconfig.org
Example: https://github.com/toddmotto/fluidvids/blob/master/.editorconfig
via #4
Hi, still me :D
See this pen:
https://codepen.io/smcyr/pen/Krbxow
In this particular implementation, I would like the error message to be positioned below the 3 radio buttons (which are hidden and displayed as grey blocks) which is not the case.
Maybe there could be a data attribute like data-error-message="category"
where you specify the input name inside. This data attribute could be added to a
See this test case and click on submit without filling anything. There should be 3 error messages (like native validation) but there is only 1. If you check one, the error message disappear, but the other two checkboxes still don't have error messages and if you check them too, they still have the error css class. Thanks!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test Validation</title>
<style>
.error {
border-color: red;
color: red;
}
.error + label {
color: red;
}
.error-message {
color: red;
}
</style>
</head>
<body>
<form>
<input id="category-1" type="checkbox" required="required" name="category[]" value="category-1"><label for="category-1">Category 1</label>
<input id="category-2" type="checkbox" required="required" name="category[]" value="category-2"><label for="category-2">Category 2</label>
<input id="category-3" type="checkbox" required="required" name="category[]" value="category-3"><label for="category-3">Category 3</label>
<br>
<button>Submit</button>
</form>
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/bouncer/dist/bouncer.polyfills.min.js"></script>
<script>
var validate = new Bouncer('form', {
messageAfterField: false
});
</script>
</body>
</html>
Hello,
I would like to use two form in a page. But I do not know how can call bouncerFormValid two time ?
For example
document.addEventListener('bouncerFormValid', function (event) { var form = event.target; }, false);
Update to Gulp 4 via https://github.com/cferdinandi/gulp-boilerplate. Gulp will run locally as installed dependency instead of globally.
Via #4
We use a three field style Date of Birth pattern with a month select, day input, and year input.
I have a Javascript function to validate the age > 5 , < 110 (see below);
validateAge(year,month,day) {
const max_year = new Date().getFullYear() - 110 ;
const min_year = new Date().getFullYear() - 5 ;
const _month = new Date().getMonth() + 1;
const _day = new Date().getDay();
const dateofbirthDate = new Date(year + "-"+month+"-"+day);
const mindate = new Date( min_year+ '-'+_month+'-'+_day);
const maxdate = new Date(max_year+ '-'+_month+'-'+_day);
if(dateofbirthDate <= mindate && dateofbirthDate >= maxdate){
return true;
}
else
return false;
}
We use bouncer for our validation, but how would I/could I incorporate this in to bouncer with customValidations?
It would be great to have async custom validations, e.g. for doing remote validation. Would you consider a PR changing the API to being async by default? Or would you recommend another approach?
There's some little things that can make easier for others to contribute to the project:
<input type="number">
is not correctly detected.
The error reported is always Please fill out this field and not Please enter a number as it should be. You may see this behaviour on your demo page. Try to insert some letters in the 'Number' field.
A workaround could be using pattern
with type="text"
but the error reported would be a generic Please match the requested format.
On the other hand <input type="email">
and <input type="url">
reports the error correctly (Please enter a valid email address or Please enter a URL).
Regards
There is an error
class, but no corresponding success
class. This would be very useful for styling fields that have been correctly filled out.
Thanks for providing Bouncer, a super handy and light package!
One development experience issue I ran into, was trying to preventDefault from the form onsubmit event, and it appeared to have no effect.
I called preventDefault in my onsubmit handler, and was awaiting a fetch response, but the form would always submit, before I could process the response.
Not until I spotted the 'disableSubmit' option, did I realize I had to set that as true to completely prevent submit from occurring.
Maybe there is opportunity to state that more explicitly in the readme, in hopes of helping someone else avoid running in to this scenario. Or perhaps, I just missed something obvious, and should have read the docs in greater detail!
Regardless, I find Bouncer very practical and useful!
Much appreciated. Steve.
Hi!
Do you forgive me for not submit a test case? This is a matter of documentation.
The native validation of the pattern
attribute modifies its value a little, before test it.
Shouldn't it be something like '^(?:' + field.getAttribute('pattern') + ')$'
to respect the same rules?
I'm sorry for being the first annoying guy to open an issue.
Possibly not bug, maybe just limitation - validating a group of checkboxes where at least one is required: https://codepen.io/iamkeir/pen/jgzOJr?editors=1010
However, if you assign values to the checkboxes, the above starts outputting multiple error messages... which seems odd: https://codepen.io/iamkeir/pen/wVmKyV?editors=1010
Possibly related to #17?
No need for fork or test case, the problem is a simple typo in your code. the .destroy function fails because your custom wrapper forEach is mis-spelled as formEach (see below for a snippet of your code). The typo causes destroy to fail.
var removeAllErrors = function (selector, settings) { forEach(document.querySelectorAll(selector), function (form) { formEach(form.querySelectorAll('input, select, textarea'), function (field) { removeError(field, settings); }); }); };
thanks
The bouncerFormValid
event only fires once all fields are valid AND you re-submit the form. Expected behaviour would be to fire event as soon as fields are valid, as per bouncerFormInvalid
.
Test case: https://codepen.io/iamkeir/pen/PMRvzp
How can I check if at least one certificate has been added?
The problem is that with zero certificates there is no input for validation either.
A wrapper should have:
data-bouncer-group="atLeastOneCertificate"
And then it checks if there is in input with value in the wrapper.
But how can I do that with bouncer.js?
CustomValidations need an "input, select, textarea"
For radio button groups, the error class is added to all the radio buttons from the group, but if it's validated, the error class is removed only from the first.
Is there a way to disable validation on field blur?
Hi,
I am using a validation pattern
on a input[type="text"]
and it passes this script but doesn't pass the native Browser API.
<input required
type="text"
name="first-name"
placeholder="Please try: 23fd"
min-length="2"
max-length="20"
title="Enter your first name. Only letters allowed."
pattern="[a-zA-Z]+">
Same result with: pattern="\D"
.
Please see: https://codepen.io/smarian/pen/KbpqJr
Test case:** https://codepen.io/danb-cws/pen/wRopqa
(note pen console shows some React error?)
(Note my other issue: Lib is not initialising above version 1.2.1 (polyfill version or non-polyfill) )
Using the (functioning) v 1.2.1 version on Chrome
An email address in the form a@b is marked with the Bouncer error, but the submit is 'ungreyed' non-disabled in this state. The form will not submit however until the field is edited to [email protected]
I understand that emails of the form a@b are perfectly valid in the spec, so I imagine this is due to a difference in the regex used in Bouncer on the field vs the HTML5 validation on the containing form
Screenshot:
What the title says.
Hey Chris,
Using your demo code I added a fieldset wrapper around the form field div containers. When I click submit, validation never completes (no error styles, error text). When fieldset is removed everything works as intended.
One error shows in DevTools :
TypeError: e.value is undefined[Learn More] _display:121:1 u http://fiddle.jshell.net/_display/:121:1 f http://fiddle.jshell.net/_display/:121:7204 window.onload/</</l.validate http://fiddle.jshell.net/_display/:121:9042 m/n< http://fiddle.jshell.net/_display/:121:9427 filter self-hosted:318:17 m http://fiddle.jshell.net/_display/:121:9362
Test case: https://codepen.io/finstah/pen/vQymoB
There is no way of resetting validation alongside form itself.
Or at least I haven't found one.
So if you have a form, say, in a popup, you want to reset it everytime user closes it. But errors still remain.
A method to reset all errors and validated fields will be magnificent.
If I set up a form to be validated, it works beautifully. But if I try to incorporate Google Recaptcha into the submit process, the field validation stops working.
I suspect that this is a Google issue, but getting them to change anything seems a forlorn hope. Is there a fix or a workaround, or do I have to choose between Bouncer and Recaptcha?
Hey,
Is it possible to look for aria-required
.
I have such a situation that there is no required
but is aria-required
and I can't change the HTML code.
Or I will build a custom validation then.
Useful for fields that validate without any errors first time out.
Test case:** https://codepen.io/danb-cws/pen/wRopqa
(note pen console shows some React error?)
Lib is not initialising above version 1.2.1 (polyfill version or non-polyfill)
(with >= 1.2.2 only native html5 validation cuts in)
Tested chrome and firefox, same result
I would like to install it with npm install bouncer --save
and after that, import it like import { Bouncer } from 'bouncer';
. Thanks!
Hey,
How about:
Check Password Confirmation - so compare 2 fields for example like data-bouncer-compare="password-check"
or something like that.
Checkboxes - how to check if some amount is checked like at least 3?
Some reference:
http://www.formvalidator.net/#default-validators_checkboxgroup
Currently if a form contains a not visible field (e.g. with css display: none) it will get validated.
This creates a problem with template elements in DOM which are used to create new, visible items on webpage.
Possible options:
Hi,
Any plan for add some translation/localization mechanism for error messages? I would help if you like.
Bonjour,
I would like to validate a checkbox group with the latest version of bouncer.js 1.4.3 as the following CodePen:
https://codepen.io/anon/pen/KENaor
There must be at least one or more boxes checked but not necessarily all with a single error message.
Is it possible?
In what way.
Thank you for your reply.
I am using another JS library to create the 'floating labels' effect, and it interferes with the functionality of Bouncer because it wraps the fields of the form in their own <div>
when it initiates. This confuses Bouncer's error message injection, causing an error when it tries to find the parentNode
: Uncaught TypeError: Cannot read property 'parentNode' of null
Oddly, setting messageAfterField: false
option is a workaround for this.
See both the error and the workaround in this codepen:
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.