• Stars
    star
    230
  • Rank 167,618 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight form validation script.

Validate.js Build Status

A lightweight form validation script that augments native HTML5 form validation elements and attributes, providing a better user experience and giving you more control.

When a visitor leaves a field, Validate.js immediately validates the field and displays an error if applicable. It also validates the entire form on submit, and provides support for custom onSubmit() functions (for example, Ajax form submission).

View the demo

Deprecation Notice

This plugin has been deprecated and replaced with Bouncer, which uses the came conventions but has better under-the-hood engineering.

Validate.js attempted to use the Constraint Validation API to validate fields. The API is buggy at best, and smoothing it across browsers became an increasingly difficult task. As a result, I wrote an entirely new plugin from the ground-up.

Because this plugin was featured in my CSS Tricks series, I'm leaving it up in read only mode for archival purposes.

It will no longer be maintained or updated.


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 Validate.js on your site.

There are two versions of Validate: the standalone version, and one that comes preloaded with a polyfill for the Validaty State API, which is only supported in newer browsers and implemented inconsistently.

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

Direct Download

You can download the files directly from GitHub.

<script src="path/to/validate.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. Validate uses semantic versioning.

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

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

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

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

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

2. Use HTML5 semantic input types and validation-related attributes on your form fields.

Add the required attribute to required fields. Use type="email" and type="url" for email addresses and URLs, respectively. Include pattern attributes, min and max, and so on to set validation criteria for your form fields. View a full list of types and attributes on MDN.

<div>
	<label for="email">Email</label>
	<input type="email" id="email" required>
</div>

<div>
	<label for="url">URL</label>
	<input type="url" id="url" required>
</div>

If you're using validation patterns, you can also include a title with a custom validation message. This will display in the error message.

<div>
	<label for="password">Password (At least 1 uppercase character, 1 lowercase character, and 1 number)</label>
	<input type="password" id="password" value="" title="Please choose a password that includes at least 1 uppercase character, 1 lowercase character, and 1 number." pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required>
</div>

3. Flag your form for validation.

Add the [data-validate] attribute to any forms you want validated.

<form data-validate>
	...
</form>

4. Initialize Validate.js.

In the footer of your page, after the content, initialize Validate.js. And that's it, you're done. Nice work!

<script>
	validate.init();
</script>

ES6 Modules

Validate does not have a default export, but does support CommonJS and can be used with native ES6 module imports.

import('/path/to/validate.polyfills.min.js')
	.then(function () {
		validate.init();
	});

It uses a UMD pattern, and should also work in most major module bundlers and package managers.

Styling Errors

Validate.js 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;
}

Working with the Source Files

If you would prefer, you can work with the development code in the src directory using the included Gulp build system. This compiles, lints, and minifies code.

Dependencies

Make sure these are installed first.

Quick Start

  1. In bash/terminal/command line, cd into your project directory.
  2. Run npm install to install required files.
  3. When it's done installing, run one of the task runners to get going:
    • gulp manually compiles files.
    • gulp watch automatically compiles files when changes are made and applies changes using LiveReload.

Options and Settings

Validate.js 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.

Global Settings

You can pass options and callbacks into Validate through the init() function:

validate.init({

	// Classes and Selectors
	selector: '[data-validate]', // The selector for forms to validate
	fieldClass: 'error', // The class to apply to fields with errors
	errorClass: 'error-message', // The class to apply to error messages

	// Messages
	messageValueMissing: 'Please fill out this field.', // Displayed when a required field is left empty
	messageValueMissingCheckbox: 'This field is required.', // Displayed when a required checkbox isn't checked
	messageValueMissingRadio: 'Please select a value.', // Displayed when a required radio button isn't selected
	messageValueMissingSelect: 'Please select a value.', // Displayed when an option from a required select menu isn't selected
	messageValueMissingSelectMulti: 'Please select at least one value.', // Displayed when an option from a require multi-select menu isn't selected
	messageTypeMismatchEmail: 'Please enter an email address.', // Displayed when a `type="email"` field isn't a valid email
	messageTypeMismatchURL: 'Please enter a URL.', // Displayed when a `type="url"` field isn't a valid URL
	messageTooShort: 'Please lengthen this text to {minLength} characters or more. You are currently using {length} characters.', // Displayed with the `minLength` attribute is used and the input value is too short
	messageTooLong: 'Please shorten this text to no more than {maxLength} characters. You are currently using {length} characters.', // Displayed with the `maxLength` attribute is used and the input value is too long
	messagePatternMismatch: 'Please match the requested format.', // Displayed with the `pattern` attribute is used and the pattern doesn't match (if a `title` attribute is used, that's displayed instead)
	messageBadInput: 'Please enter a number.', // Displayed when the field is numeric (ex. `type="number"`) but the value is not a number
	messageStepMismatch: 'Please select a valid value.', // Displayed when the `step` attribute is used and the value doesn't adhere to it
	messageRangeOverflow: 'Please select a value that is no more than {max}.', // Displayed with the `max` attribute is used and the input value is too hight
	messageRangeUnderflow: 'Please select a value that is no less than {min}.', // Displayed with the `mind` attribute is used and the input value is too low
	messageGeneric: 'The value you entered for this field is invalid.', // A catchall error, displayed when the field fails validation and none of the other conditions apply

	// Form Submission
	disableSubmit: false, // If true, don't submit the form to the server (for Ajax for submission)
	onSubmit: function (form, fields) {}, // Function to run if the form successfully validates

	// Callbacks
	beforeShowError: function (field, error) {}, // Function to run before an error is display
	afterShowError: function (field, error) {}, // Function to run after an error is display
	beforeRemoveError: function (field) {}, // Function to run before an error is removed
	afterRemoveError: function (field) {}, // Function to run after an error is removed

});

Use Validate.js events in your own scripts

You can also call Validate.js's public methods in your own scripts.

hasError()

Check if a field has a validation error.

validate.hasError(
	field, // The field to validate
	options // User settings, same as the ones passed in during validate.init() [optional]
);

Example

var field = document.querySelector('[name="email"]');
var error = validate.hasError(field);

if (error) {
	// Do something...
}

showError()

Show an error message on a field.

validate.showError(
	field, // The field to show an error message for
	error, // The error message to show
	options // User settings, same as the ones passed in during validate.init() [optional]
);

Example 1: Write your own error

var field = document.querySelector('[name="email"]');
var error = 'This field is wrong, dude!';
validate.showError(field, error);

Example 2: Using hasError()

var field = document.querySelector('[name="url"]');
var error = validate.hasError(field);
validate.showError(field, error);

removeError()

Remove the error message from a field.

/**
 * Remove an error message from a field
 * @public
 * @param  {Node}   field   The field to remove the error from
 * @param  {Object} options User options
 */
validate.removeError(
	field, // The field to remove the error from
	options // User settings, same as the ones passed in during validate.init() [optional]
);

Example

var field = document.querySelector('[name="email"]');
validate.removeError(field);

destroy()

Destroy the current validate.init(). Removes all errors and resets the DOM. This is called automatically during the init function to remove any existing initializations.

validate.destroy();

Browser Compatibility

Validate.js works in all modern browsers, and (mostly) IE 10 and above.

Unfortunately, not all validation types are supported by all versions of IE and Edge consistently. For example, IE10 and IE11 will check if a form input is too long (using the maxLength attribute), but Edge will not. And no version of IE or Edge will check if it's too short (using the minLength attribute).

Polyfills

Use the included polyfill version of Validate (or include your own) to push support back to IE10, and add missing features to partially supported browsers.

If you also include Eli Grey's classList.js polyfill, you can push support even further, back to IE9.

License

The code is available under the MIT License.

More Repositories

1

smooth-scroll

A lightweight script to animate scrolling to anchor links.
JavaScript
5,481
star
2

reef

A lightweight library for creating reactive, state-based components and UI.
JavaScript
1,058
star
3

gulp-boilerplate

A boilerplate for building web projects with Gulp.js.
JavaScript
846
star
4

kraken

A lightweight, mobile-first boilerplate for front-end web developers.
HTML
768
star
5

gumshoe

A simple vanilla JS scrollspy script.
JavaScript
731
star
6

social-sharing

Add social sharing links and buttons without the bloat.
CSS
641
star
7

tabby

Lightweight, accessible vanilla JS toggle tabs.
JavaScript
577
star
8

atomic

A tiny, Promise-based vanilla JS Ajax/HTTP plugin with great browser support.
HTML
540
star
9

build-tool-boilerplate

A simple boilerplate for using NPM tasks to build and compile JavaScript, CSS, and image files.
JavaScript
484
star
10

bouncer

A lightweight form validation script that augments native HTML5 form validation elements and attributes.
JavaScript
304
star
11

houdini

A simple, accessible show-and-hide/accordion script.
JavaScript
158
star
12

ebook-boilerplate

A lightweight boilerplate for self-publishing ebooks with markdown and command line.
CSS
135
star
13

htaccess

[DEPRECATED] Best practice server rules for making web pages fast and secure.
ApacheConf
93
star
14

slider

[DEPRECATED] A simple, fluid, touch-enabled carousel.
JavaScript
87
star
15

right-height

Dynamically set content areas of different lengths to the same height.
CSS
87
star
16

modals

Simple modal dialogue windows
JavaScript
85
star
17

bin

A tiny (<1kb) localStorage and sessionStorage helper library.
JavaScript
83
star
18

vanilla-javascript-cheat-sheet

Moved
80
star
19

drop

A small CSS component that turns browser-native <details> elements into dropdown menus.
JavaScript
75
star
20

vanilla-js-toolkit

A growing collection of vanilla JavaScript code snippets, helper functions, polyfills, plugins, and learning resources.
CSS
74
star
21

form-saver

A simple script that lets users save and reuse form data.
JavaScript
68
star
22

hugo-starter

A barebones starter project and theme for learning Hugo.
HTML
67
star
23

gmt-wordpress-for-web-apps

[DEPRECATED] A plugin that provides the essential components you need to power your web app with WordPress.
PHP
67
star
24

gmt-html-minify

Minify your HTML output in WordPress.
PHP
61
star
25

events

A tiny event delegation library.
JavaScript
61
star
26

buoy

[DEPRECATED] A lightweight collection of helper methods for getting stuff done with native JavaScript.
JavaScript
54
star
27

astro

Mobile-first navigation patterns.
JavaScript
53
star
28

sticky-footer

Dynamic, responsive sticky footers.
JavaScript
47
star
29

keel

A lightweight boilerplate for WordPress theme developers.
JavaScript
46
star
30

x-ray

X-Ray is a script that lets users toggle password visibility in forms.
JavaScript
46
star
31

table-of-contents

Automatically generate a table of contents from the headings on the page.
JavaScript
38
star
32

jar

A tiny (< 1kb) library that makes working with cookies easier.
JavaScript
37
star
33

saferInnerHTML

Set the HTML of an element while protecting yourself from XSS attacks.
JavaScript
29
star
34

dom-manipulation-source-code

HTML
24
star
35

gmt-image-compress-and-sharpen

[DEPRECATED] Change the default WordPress compression rate for JPGs, convert images to progressive JPGs, and sharpen images.
PHP
19
star
36

jellyfish

[DEPRECATED] A progressively enhanced image lazy loader.
JavaScript
18
star
37

learn-vanilla-js

A roadmap for learning vanilla JavaScript
HTML
18
star
38

frontend-horse-js-library

The boilerplate for the Frontend Horse livestream.
JavaScript
15
star
39

state-based-ui-source-code

JavaScript
15
star
40

petfinderAPI4everybody

A JavaScript plugin that makes it easier to use the Petfinder API.
JavaScript
14
star
41

wp-shopping-cart

[DEPRECATED - DO NOT USE] A simple PayPal shopping cart for WordPress.
PHP
14
star
42

alerts

Simple alert messages.
JavaScript
14
star
43

wp-theme-options

[DEPRECATED] Create a theme options menu that admin can use to adjust theme settings from the dashboard.
PHP
14
star
44

reef-js

The website for ReefJS.
HTML
13
star
45

progress-bars

Simple CSS progress bars.
CSS
13
star
46

writing-libraries-source-code

HTML
13
star
47

learn-vanilla-js-source-code

HTML
12
star
48

vanilla-js-guides

HTML
12
star
49

kelp

A collection of small functions for creating reactive, state-based UIs.
JavaScript
12
star
50

project-star-rating-system

A vanilla JavaScript project
HTML
11
star
51

gmt-mailchimp-wp-rest-api

Add WP Rest API hooks for JS use of the Mailchimp API.
PHP
11
star
52

apis-source-code

HTML
11
star
53

vanilla-js-list

A growing list of organizations that build sites and apps with vanilla JS
CSS
10
star
54

petfinder-api-for-wordpress

A collection of functions to help you display Petfinder listings on your WordPress site.
PHP
10
star
55

browser-storage-source-code

HTML
10
star
56

gmt-pricing-parity

Display country-specific EDD discounts to visitors.
PHP
9
star
57

snapshot

Simple image styling.
CSS
9
star
58

sw-fonts

Demo for https://gomakethings.com/improving-web-font-performance-with-service-workers/
HTML
9
star
59

gmt-remove-header-junk

[DEPRECATED] Remove the unneccessary junk WordPress adds to the header.
PHP
9
star
60

dom-injection-source-code

HTML
8
star
61

gmt-paypal-ipn-forwarder

[DEPRECATED] Forward PayPal IPN to multiple other IPN services in WordPress.
PHP
8
star
62

service-worker-pages-demo

A demo for https://gomakethings.com/saving-recently-viewed-pages-with-service-workers-and-vanilla-js/
HTML
8
star
63

gmt-slack-invites-for-edd

[DEPRECATED] Automatically invite members to your Slack team when they purchase a product.
PHP
8
star
64

vanilla-js-guidebook-labs

The labs for "The Vanilla JS Guidebook."
HTML
7
star
65

the-lean-web

CSS
7
star
66

vanilla-js-academy

PHP
7
star
67

service-workers-source-code

JavaScript
7
star
68

sw-offline-first

Demo for https://gomakethings.com/offline-first-with-service-workers-and-vanilla-js/
HTML
7
star
69

harbor-wp-theme

A free mobile-friendly WordPress theme built specifically for animal rescue organizations.
JavaScript
7
star
70

adventure

A simplish, imagination-based kitchen table RPG.
CSS
7
star
71

variable-function-scope-source-code

HTML
6
star
72

gmt-automated-slack-invites

Automate Slack invites with WordPress.
PHP
6
star
73

google-hosted-jquery

[DEPRECATED] Use the Google CDN version of jQuery in WordPress, with a local fallback.
PHP
6
star
74

games

Simple vanilla JS game demos.
HTML
5
star
75

vanilla-js-projects

HTML
5
star
76

gomakethings

The WordPress theme for Go Make Things
JavaScript
5
star
77

service-worker-demo

A demo for https://gomakethings.com/writing-your-first-service-worker-with-vanilla-js/
HTML
5
star
78

origami

[DEPRECATED] Origami has been merged into the Kraken front-end boilerplate and is no longer supported.
HTML
5
star
79

timezones

Easily calculate timezones for your next meeting.
HTML
4
star
80

arrays-objects-source-code

HTML
4
star
81

labels

Lightweight CSS labels.
CSS
4
star
82

gmt-antispambot

A shortcode for the antispambot function that's built into WordPress.
PHP
4
star
83

cferdinandi

4
star
84

web-components-source-code

HTML
4
star
85

string-array-object-source-code

HTML
4
star
86

es-modules-demo

https://gomakethings.com/an-intro-to-import-and-export-with-es-modules/
JavaScript
3
star
87

es-modules-source-code

JavaScript
3
star
88

ajax-source-code

HTML
3
star
89

strings-numbers-source-code

HTML
3
star
90

gmt-donations

[DEPRECATED] A WordPress plugin that lets you create powerful donation forms that integrate with Stripe and PayPal Express Checkout.
PHP
3
star
91

go-mobile-first

[DEPRECATED] A mobile-first boilerplate for WordPress.
PHP
3
star
92

gmt-allow-iframes

[DEPRECATED] Prevent wp_kses from removing iframe embeds
PHP
3
star
93

advanced-academy-common-issue-not-modularizing-your-code-enough

JavaScript
3
star
94

token-based-authentication-source-code

HTML
3
star
95

vanilla-js-podcast

A show about JavaScript for people who hate the complexity of modern frontโ€‘end web development.
CSS
3
star
96

fetch

The Fetch for Petfinder plugin
JavaScript
2
star
97

javascript-essentials-source-code

Source code for the JavaScript Essentials workshop.
HTML
2
star
98

es-modules-default

https://gomakethings.com/how-to-define-a-default-export-with-vanilla-js-es-modules/
JavaScript
2
star
99

accessible-components-source-code

HTML
2
star
100

careers

CSS
2
star