Git Product home page Git Product logo

validate's Introduction

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.

validate's People

Contributors

cferdinandi avatar floedelmann avatar robinwhittleton 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  avatar  avatar  avatar  avatar

validate's Issues

MailChimp demo not working right

https://codepen.io/cferdinandi/pen/MorBEp

I tested it on Firefox PC, then Safari on Mac OS. Now just retested it.
Finally also tested on iPad and iPhone, everywhere same result.
Now the subscription widget on your blog works magic.

Now to see the two fields popping, you have to submit two different errors in email field or fix the blur to onblur which then gets the event listener to work.

Alternatively you first enter a mistake email like “mistake”, then “mistake@“ or “mistake@c.” and it looks like further down:

pastedgraphic-3

Switch to a loop for support test

var validityObjProperties = ["badInput", "patternMismatch", "rangeOverflow", "rangeUnderflow", "stepMismatch", "tooLong", "tooShort", "typeMismatch", "valid", "valueMissing"];

var supported = function () {
      var input = document.createElement('input');
      if('validity' in input) {
        var supportObj = { lackSupport: false, unsupportedProps: [] };
        for(var i = 0; i < validityObjProperties.length; i++) {
          var validityProp = validityObjProperties[i];
          var isPropSupported = validityProp in input;
           if(!isPropSupported) { 
              supportObj.lackSupport = true;
              supportObj.unsupportedProps.push(validityProp);
           }
        }
      }

  return supportObj;
};

Via Konstantin

validate.destroy not working

Had to replace the line in validate.destroy:
var fields = document.querySelectorAll(settings.errorClass)
with
var fields = document.querySelectorAll('.' + settings.fieldClass);

Should capturing be set to true when removing the blur handler?

In validate.init() you attach a listener to the blur event, with capturing set to true, like so:

document.addEventListener('blur', blurHandler, true);

But in validate.destroy() that same listener is removed with capturing set to false:

document.removeEventListener('blur', blurHandler, false);

Should capturing be set to true when removing the listener, in order to be consistent? Pardon me if I'm wrong. Maybe it doesn't matter?

Event listeners registered by rails-ujs override/hijack the one added by validate.init()

I'm using Rails 5 and rails-ujs and had to do a few things to get this library running smoothly:

rails-ujs (a javascript driver added by rails) attaches its own submit event listeners to the document. When a form with data-remote=true is submitted, the rails-ujs event listener kicks in and submits the form via ajax. This prevents the submit listener added by validate.init() from 'running'.

To fix this I had to two things:

1 - Use capturing. I had to change from the following:

document.addEventListener('submit', submitHandler, false);

to this:

document.addEventListener('submit', submitHandler, true);

2 - Stop propagation on failed validation:

// Prevent form from submitting if there are errors or submission is disabled
if (hasErrors || settings.disableSubmit) {
  event.preventDefault();
  event.stopPropagation();
}

Now everything works fine.

It's worth pointing out, that the blur handler and click handler are not affected by rails-ujs at all, they work as expected, it's just the submit handler that fails to do run when a form is submitetd via XHR.

Custom message per input

Hi there!

I'm replacing the standard form validation in my company, and this seems like a great fit! There's one thing i'm unsure about though: custom and/or variable error messages per input. Often we use messages like "You need to fill out your last name" for example. "last name" here is variable, it only holds true for 1 particular field. I tried doing something like this:

beforeShowError: function (field, error) {
    // error would be "You need to fill out your {label}"
    error.replace('{label}', field.getAttribute('data-label'));
}

But it didn't change the error message. In fact, I can't seem to change the error message at all in the event callbacks. I think the problem is the fact that you don't know what error 'type' is going to show. What I did now is add this for each error type in the hasError function:

// If too short
if (validity.tooShort) {
    if (field.getAttribute('data-error-tooshort')) {
        return field.getAttribute('data-error-tooshort');
    } else {
        return localSettings.messageTooShort.replace('{minLength}', field.getAttribute('minLength')).replace('{length}', field.value.length);
    }
}

But it feels a bit hacky, is there some way of adding it into event callbacks?

Thank you!

Remove corrected errors in submit handler

Hi,

the submit handler does not remove previous errors that were fixed. When the user makes another attempt to submit it would be useful to reduce the errors to only show those that are persisting.

Or is this behavior intentional?

Regards,
Micha

Add a disabled attribute to the submit when not validated?

Just started playing with the plugin. Really nice, thanks.

I'm using the disableSubmit: true to stop the form being submitted if not validated. Is there a way to pass a disabled attribute to the submit input when it's not validated? Functionally it work, bit it would just be nice to provide a visual indicator that the form cannot be submitted.

Unless I'm missing a way to do this already?

Cross Browser problems with checkboxes and radios.

Hi, there seem to be some problems with checkboxes and radios on your demo page These impact different browsers in different ways.

Chrome 61 Mac - Radio buttons
Selecting 'Yes' is valid, selecting 'No' is invalid

Safari 11 Mac - Radio buttons
'Yes' and 'No' are both invalid

Firefox 55. - Radio buttons
'Yes' and 'No' are both invalid

Chrome 61 - Checkboxes
Only "Wolverine" is valid

Safari 11 - Checkboxes
No options are valid

Firefox 55 - Checkboxes
No options are valid

Custom error for specific input types

Hey there, firstly - love the package, it's wicked!

Not sure if a bug or feature request but I can't find a simple way to change the typical required error message for, say, a 'do you accept.. ' checkbox as "Please fill out this field." doesn't quite ring true.

Also, this should totally be a legit npm package. Installing it through github is.. fine.. but it breaks if you subsequently install another package - you have to delete node_modules and re-install it all (for reason that are beyond me).

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.