Coder Social home page Coder Social logo

cferdinandi / bouncer Goto Github PK

View Code? Open in Web Editor NEW
306.0 11.0 44.0 553 KB

A lightweight form validation script that augments native HTML5 form validation elements and attributes.

License: MIT License

JavaScript 68.07% HTML 31.63% HCL 0.30%
vanilla-js javascript javascript-plugin form-validation

bouncer's Introduction

Bouncer.js Build Status

A lightweight form validation script that augments native HTML5 form validation elements and attributes.

View the Demo on CodePen →

Getting Started | Form Validation Attributes | Error Styling | Error Types | Custom Validations | Error Location | API | Browser Compatibility | License |

Features:

  • Fields validate on blur (as the user moves out of them), which data shows is the best time for cognitive load.
  • The entire form is validated on submit.
  • Fields with errors are revalidated as the user types. Errors are removed the instant the field is valid.
  • Supports custom validation patterns and error messages.

Want to learn how to write your own vanilla JS plugins? Check out my Vanilla JS Pocket Guides or join the Vanilla JS Academy and level-up as a web developer. 🚀


Getting Started

Compiled and production-ready code can be found in the dist directory. The src directory contains development code.

1. Include Bouncer on your site.

There are two versions of Bouncer: the standalone version, and one that comes preloaded with polyfills for closest(), matches(), classList, and CustomEvent(), which are only supported in newer browsers.

If you're including your own polyfills or don't want to enable this feature for older browsers, use the standalone version. Otherwise, use the version with polyfills.

Direct Download

You can download the files directly from GitHub.

<script src="path/to/bouncer.polyfills.min.js"></script>

CDN

You can also use the jsDelivr CDN. I recommend linking to a specific version number or version range to prevent major updates from breaking your site. Smooth Scroll uses semantic versioning.

<!-- Always get the latest version -->
<!-- Not recommended for production sites! -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/bouncer/dist/bouncer.polyfills.min.js"></script>

<!-- Get minor updates and patch fixes within a major version -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/bouncer@1/dist/bouncer.polyfills.min.js"></script>

<!-- Get patch fixes within a minor version -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/[email protected]/dist/bouncer.polyfills.min.js"></script>

<!-- Get a specific version -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/[email protected]/dist/bouncer.polyfills.min.js"></script>

NPM

You can also use NPM (or your favorite package manager).

npm install formbouncerjs

2. Add browser-native form validation attributes to your markup.

No special markup needed—just browser-native validation attributes (like required) and input types (like email or number).

<form>
	<label for="email">Your email address</label>
	<input type="email" name="email" id="email">
	<button>Submit</button>
</form>

3. Initialize Bouncer.

In the footer of your page, after the content, initialize Bouncer by passing in a selector for the forms that should be validated.

If the form has errors, submission will get blocked until they're corrected. Otherwise, it will submit as normal.

And that's it, you're done. Nice work!

<script>
	var validate = new Bouncer('form');
</script>

Form Validation Attributes

Modern browsers provide built-in form validation.

Bouncer hooks into those native attributes, suppressing the native validation and running its own. If Bouncer fails to load or run, the browser-native validation will run in its place.

Required fields

Add the required attribute to any field that must be filled out or selected.

<input type="text" name="first-name" required>

Special Input Types

You can use special type attribute values to indicate specific types of data that should be captured.

<!-- Must be a valid email address -->
<input type="email" name="email">

<!-- Must be a valid URL -->
<input type="url" name="website">

<!-- Must be a number -->
<input type="number" name="age">

<!-- Must be a date in YYYY-MM-DD format (many browsers include a native date picker for this) -->
<input type="date" name="dob">

<!-- Must be a time in 24-hour format (many browsers include a native date picker for this) -->
<input type="time" name="time">

<!-- Must be a month/year in YYYY-MM format (many browsers include a native date picker for this) -->
<input type="month" name="birthday">

<!-- Must be a color in #rrggbb format (many browsers include a native color picker for this) -->
<input type="color" name="color">

Min and Max Values

For numbers that should not go below or exceed a certain value, you can use the min and max attributes, respectively.

<!-- Cannot exceed 72 -->
<input type="number" max="72" name="answer">

<!-- Cannot be below 37 -->
<input type="number" min="37" name="answer">

<!-- They can also be combined -->
<input type="number" min="37" max="72" name="answer">

Min and Max Length

For inputs that should not be shorter or longer than a certain number of characters, you can use the minlength and maxlength attributes, respectively.

<!-- Cannot be shorter than 12 characters -->
<input type="password" minlength="12" name="password">

<!-- Cannot be longer than 24 characters -->
<input type="text" maxlength="24" name="first-name">

<!-- They can also be combined -->
<input type="text" minlength="7" maxlength="24" name="favorite-pixar-character">

Custom Validation Patterns

You can use your own validation pattern for a field with the pattern attribute. This uses regular expressions.

<!-- Phone number be in 555-555-5555 format -->
<input type="text" name="tel" pattern="\d{3}[\-]\d{3}[\-]\d{4}">

Custom Pattern Mismatch Error Messages

Show custom errors for pattern mismatches by adding the [data-bouncer-message] attribute to the field.

<!-- Phone number be in 555-555-5555 format -->
<input type="text" name="tel" pattern="\d{3}[\-]\d{3}[\-]\d{4}" data-bouncer-message="Please use the following format: 555-555-5555">

Error Styling

Bouncer does not come pre-packaged with any styles for fields with errors or error messages. Use the .error class to style fields, and the .error-message class to style error messages.

Need a starting point? Here's some really lightweight CSS you can use.

/**
 * Form Validation Errors
 */
.error {
	border-color: red;
}

.error-message {
	color: red;
	font-style: italic;
	margin-bottom: 1em;
}

Error Types

Bouncer captures four different types of field errors:

  • missingValue errors occur when a required field has no value (or for checkboxes and radio buttons, nothing is selected).
  • patternMismatch errors occur when a value doesn't match the expected pattern for a particular input type, or a pattern provided by the pattern attribute.
  • outOfRange errors occur when a number is above or below the min or max values.
  • wrongLength errors occur when the input is longer or shorter than the minlength and maxlength values.

The patterns and messages associated with these types of errors can be customized.

Custom Validation Types

You can add custom validation types to Bouncer beyond the four standard validations.

You can see this feature in action with the Confirm Password field on the demo page, and view examples of custom validations in the Cookbook (coming soon).

Adding custom validations

Pass in a customValidations object as an option when instantiating a new Bouncer instance. Each property in the object is a new validation type. Each value should be a function that accepts two arguments: the field being validated and the settings for the current instantiation.

The function should check if the field has an error. Return true if there's an error, and false when there's not.

var validate = new Bouncer('form', {
	customValidations: {
		isHello: function (field) {

			// Return false because there is NO error
			if (field.value === 'hello') return false;

			// Return true when there is
			return true;

		}
	}
});

Creating custom validation error messages

Add an error message for the custom validation by including the messages object in your options.

The key should be the same as your custom validation. It's value can be a string, or a function that returns a string. Message functions can accept two arguments: the field being validated and the settings for the current instantiation.

var validate = new Bouncer('form', {
	customValidations: {
		isHello: function (field) {

			// Return false because there is NO error
			if (field.value === 'hello') return false;

			// Return true when there is
			return true;

		}
	},
	messages: {
		// As a string
		isHello: 'This field should have a value of "hello"',

		// As a function
		isHello: function () {
			return 'This field should have a value of "hello"';
		}
	}
});

Error Message Location

By default, bouncer will render error messages after the invalid field (or the label for it, if the field is a radio or checkbox).

You can optionally render error messages before the field by setting the messageAfterField option to false.

var validate = new Bouncer('form', {
	messageAfterField: false
});

You can also assign a custom location for an error message by including the [data-bouncer-target] attribute on a field. Use a selector for where the message should go as its value.

<label for="email">Your Email Address</label>
<input type="email" name="email" id="email" data-bouncer-target="#email-error">
<p><strong>Why do we need this?</strong> We'll use your email address to send you account information.</p>
<div id="email-error"></div>

API

Bouncer includes smart defaults and works right out of the box.

But if you want to customize things, it also has a robust API that provides multiple ways for you to adjust the default options and settings.

Options and Settings

You can customize validation patterns, error messages, and more by passing and options object into Bouncer during instantiation.

var validate = new Bouncer('form', {

	// Classes & IDs
	fieldClass: 'error', // Applied to fields with errors
	errorClass: 'error-message', // Applied to the error message for invalid fields
	fieldPrefix: 'bouncer-field_', // If a field doesn't have a name or ID, one is generated with this prefix
	errorPrefix: 'bouncer-error_', // Prefix used for error message IDs

	// Patterns
	// Validation patterns for specific input types
	patterns: {
		email: /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,})+$/,
		url: /^(?:(?:https?|HTTPS?|ftp|FTP):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-zA-Z\u00a1-\uffff0-9]-*)*[a-zA-Z\u00a1-\uffff0-9]+)(?:\.(?:[a-zA-Z\u00a1-\uffff0-9]-*)*[a-zA-Z\u00a1-\uffff0-9]+)*(?:\.(?:[a-zA-Z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/,
		number: /[-+]?[0-9]*[.,]?[0-9]+/,
		color: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
		date: /(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))/,
		time: /(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9])/,
		month: /(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2]))/
	},

	// Message Settings
	messageAfterField: true, // If true, displays error message below field. If false, displays it above.
	messageCustom: 'data-bouncer-message', // The data attribute to use for customer error messages
	messageTarget: 'data-bouncer-target', // The data attribute to pass in a custom selector for the field error location

	// Error messages by error type
	messages: {
		missingValue: {
			checkbox: 'This field is required.',
			radio: 'Please select a value.',
			select: 'Please select a value.',
			'select-multiple': 'Please select at least one value.',
			default: 'Please fill out this field.'
		},
		patternMismatch: {
			email: 'Please enter a valid email address.',
			url: 'Please enter a URL.',
			number: 'Please enter a number',
			color: 'Please match the following format: #rrggbb',
			date: 'Please use the YYYY-MM-DD format',
			time: 'Please use the 24-hour time format. Ex. 23:00',
			month: 'Please use the YYYY-MM format',
			default: 'Please match the requested format.'
		},
		outOfRange: {
			over: 'Please select a value that is no more than {max}.',
			under: 'Please select a value that is no less than {min}.'
		},
		wrongLength: {
			over: 'Please shorten this text to no more than {maxLength} characters. You are currently using {length} characters.',
			under: 'Please lengthen this text to {minLength} characters or more. You are currently using {length} characters.'
		}
	},

	// Form Submission
	disableSubmit: false, // If true, native form submission is suppressed even when form validates

	// Custom Events
	emitEvents: true // If true, emits custom events

});

Custom Events

Bouncer emits five custom events:

  • bouncerShowError is emitted on a field when an error is displayed for it.
  • bouncerRemoveError is emitted on a field when an error is removed from it.
  • bouncerFormValid is emitted on a form is successfully validated.
  • bouncerFormInvalid is emitted on a form that fails validation.
  • bouncerInitialized is emitted when bouncer initializes.
  • bouncerDestroy is emitted when bouncer is destroyed.

You can listen for these events with addEventListener. All five events bubble up the DOM. The event.target is the field or form (or document, when initializing and destroying).

// Detect show error events
document.addEventListener('bouncerShowError', function (event) {

	// The field with the error
	var field = event.target;

}, false);

// Detect a successful form validation
document.addEventListener('bouncerFormValid', function (event) {

	// The successfully validated form
	var form = event.target;

	// If `disableSubmit` is true, you might use this to submit the form with Ajax

}, false);

The event.detail object holds event-specific information:

  • On the bouncerShowError event, it has the specific errors for the field.
  • On the bouncerInitialized and bouncerDestroyed events , it contains the settings for the instantiation.
  • On the bouncerFormInvalid event, it includes all of the fields with errors under event.detail.
// Detect show error events
document.addEventListener('bouncerShowError', function (event) {

	// The field with the error
	var field = event.target;

	// The error details
	var errors = event.details.errors;

}, false);

Using Bouncer methods in your own scripts

Bouncer exposes a few public methods that you can use in your own scripts.

validate()

Validate a field. Pass in the field as an argument. Returns an object with validity data.

// Get a field
var field = document.querySelector('#email');

// Validate the field
var bouncer = new Bouncer();
var isValid = bouncer.validate(field);

// Returns an object
isValid = {

	// If true, field is valid
	valid: false,

	// The specific errors
	errors: {
		missingValue: true,
		patternMismatch: true,
		outOfRange: true,
		wrongLength: true
	}

};

// You can also pass in custom options
bouncer.validate(field, {
	// ...
});

validateAll()

Validate all fields in a form or fieldset. Pass in the section as an argument. Returns an array of fields with errors.

// Get a fieldset
var fieldset = document.querySelector('#fieldset');

// Validate the field
var bouncer = new Bouncer();
var areValid = bouncer.validateAll(fieldset);

destroy()

Destroys an instantiated Bouncer instance. Removes any errors from the form and turns validation back over to the browser-native APIs.

// An bouncer instance
var bouncer = new Bouncer('form');

// Destroy it
bouncer.destroy();

Browser Compatibility

Bouncer works in all modern browsers, and IE 9 and above.

Bouncer is built with modern JavaScript APIs, and uses progressive enhancement. If the JavaScript file fails to load, browser-native form validation runs instead

Polyfills

Support back to IE9 requires polyfills for closest(), matches(), classList, and CustomEvent(). Without them, support starts with Edge.

Use the included polyfills version of Bouncer, or include your own.

License

The code is available under the MIT License.

bouncer's People

Contributors

cferdinandi avatar robsonsobral avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bouncer's Issues

scroll to input with error does not respect sticky header

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?

Age Validation

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?

File validation problems

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.

Be able to choose error message location

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

anywhere on the page and would overwrite the default position for the error message placement.
Thanks!

Email validation inconsistant - Submit button not disabled

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:

image

aria-required

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.

Validate Groups with CustomValidation?

at-least-one-certificate

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"

Google Recaptcha stops bouncer

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?

Doesn't work with inputs containing square brackets [ ] in the name

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 [ ].

Adding fieldset inside form prevents validation from working

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

Validating dynamically populated select

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.

Method typo

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

RegEx of Pattern attribute

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.

Function to validate subset of fields (e.g. a fieldset)

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.

Suggestions to the project

There's some little things that can make easier for others to contribute to the project:

  • to add an editor config file, so everybody can respect the code style easilly;
  • to allow the use of the Gulp installed dependency as an option to developers who doesn't install it globally (like me);
  • to add tests;
  • to centralize changes on CHANGELOG.md.

Reset validation

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.

getErrorLocation

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

Config of error message : Failure when defined via function + constraint is outOfRange or wrongLength

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; }

  • Cause : getErrorMessage supports both String + Function, but, for outOfRange and wrongLength, it calls String-only methods, without checking the input type :

/**
* 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}', ...

  • Solution : Perform the String-only text replacement only if input type is String.
    See pull-request #58 for proposed fix.

Error message injection fails if DOM is modified after init.

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:

Test case: https://codepen.io/matthewmcvickar/pen/omzvGd

Password strength and pls Submit another usefull customValidations

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 👍

Radio group error message placement

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.

$_POST[ 'submitted '] is missing

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?

Hidden/not visible fields are validated

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:

  • skip from validation fields that are not visible (e.g. el.type!='hidden' && el.offsetParent === null)
  • allow to manualy remove errors (like the removeError function from the prev lib: https://github.com/cferdinandi/validate)

Checkbox group validation works for only one of the group

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>

Documentation: form onsubmit preventDefault no effect without disableSubmit true

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.

IE11 error with email pattern

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)

validation of a checkbox group.

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.

Async custom validations

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?

type="number" not correctly detected

<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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.