Giter Site home page Giter Site logo

hyperform / hyperform Goto Github PK

View Code? Open in Web Editor NEW
748.0 748.0 36.0 2.92 MB

Capture form validation back from the browser

Home Page: https://hyperform.js.org

License: Other

Makefile 1.37% JavaScript 97.48% CSS 0.52% HTML 0.63%
es6 form-validation html-form html5 html5-input hyperform input javascript polyfill validation

hyperform's Introduction

Text “Hyperform - Insert Form” in 80s arcade game style

CDNJS

Capture form validation back from the browser

Hyperform is your one-stop solution for client-side form handling.

It features a complete implementation of the HTML5 form validation API in JavaScript, replaces the browser’s native methods (if they are even implemented…), and enriches your toolbox with custom events and hooks.

Not pumped yet? Then take a look at our awesome examples.

Installation

Embed from a CDN

Get up and running with Hyperform by embedding it from a CDN: CDNJS

<script src="https://cdnjs.cloudflare.com/ajax/libs/hyperform/0.9.5/hyperform.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/hyperform/0.9.5/hyperform.min.css">

or unpkg.com:

<script src="https://unpkg.com/hyperform"></script>
<link rel="stylesheet" href="https://unpkg.com/hyperform@latest/css/hyperform.css">

Install locally

The easiest way is installing via npm:

npm install hyperform

or you can use Bower:

bower install hyperform

or download the current version as ZIP archive.

Then embed dist/hyperform.min.js in your file:

<script src="path/to/hyperform/dist/hyperform.min.js"></script>

or require it in your code:

const hyperform = require('hyperform');

In old browsers you will need polyfills for the following features: WeakMap (IE 10 and lower), element.classList (IE 9 and lower), array.filter, array.every, Object.keys and Object.defineProperty (IE 8 and lower). For IE 9+ support simply add this line to use Polyfill.io’s service:

<script src="https://polyfill.io/v2/polyfill.min.js?features=Element.prototype.classList,WeakMap"></script>

Usage

You can let Hyperform take over a single form:

hyperform(document.forms[0]);

or all forms, current and future ones:

hyperform(window);

Configure settings as second argument:

hyperform(window, { revalidate: 'never' });

If you only need a certain feature once, you can access it directly by name:

if (hyperform.willValidate(some_input_element)) {
    var is_valid = hyperform.validityState(some_input_element).valid;
}

The full documentation provides you with all the nitty-gritty details and tricks.

What About the UI?

You might be wondering, how to get nifty datepickers and range sliders and stuff. Unfortunately, this is out of topic for Hyperform, but despair not! Hyperform UI (beta) is here to fill in the gaps with the help of jQuery UI.

“jQuery UI? Isn’t that that thing that they had before React?” — “No, that’s Backbone.” — “But before that?” — “No, that was Kendo.” — “...?”

If you had these thoughts right now, rest assured. For the purpose of input widgets there is still close to no other library, that is complete, themable, accessible and has wide browser support. Just try it yourself!

Examples

Yes, please! The more the better.

Status

The target is 100% support for the HTML5 validation API. Currently supported:

feature status
willValidate 🌕
setCustomValidity(message) 🌕
validity.valueMissing 🌕
validity.typeMismatch 🌕
validity.patternMismatch 🌕
validity.tooLong 🌕
validity.tooShort 🌕
validity.rangeUnderflow 🌕
validity.rangeOverflow 🌕
validity.stepMismatch 🌕
validity.badInput 🌕
validity.customError 🌕
validity.valid 🌕
checkValidity() 🌕
reportValidity() 🌕
validationMessage 🌕
valueAsDate 🌕
valueAsNumber 🌕
valueLow / valueHigh 🌑
stepUp(n) / stepDown(n) 🌕
accept attribute 🌕
support for novalidate 🌕

Current test status: View on Travis CI

Browser Support

Hyperform is fully tested and supported in

  • Chrome (latest 3)
  • Firefox (latest 3 and ESR)
  • MS Edge (latest)
  • IE down to version 9 (yes, you've read that correctly) when WeakMap for IE ≤ 10 and classList for IE 9 are polyfilled
  • Safari. Caveat: In versions ≤ 9 polyfills do not work. However, form validation and direct method calling works as expected.)

Contributing

Cool, yes! Head over to the contributing guide for details.

Changelog

We maintain an up-to date changelog named CHANGELOG.md alongside this file.

License

This library is released under the terms of the MIT license.

Contributors

Hyperform is developed by Manuel Strehl with contributions by Andrey Volynkin, Daniel Wang, Darlan Mendonça, Christoph Dörfel, Josh Farneman, Casey Corcoran, and many people reporting issues.

hyperform's People

Contributors

bennycode avatar boldewyn avatar coliff avatar dependabot[bot] avatar farneman avatar garbanas avatar mmcev106 avatar pvnr0082t avatar snaptopixel 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  avatar  avatar  avatar

hyperform's Issues

WeakMap Browser Compatibility

At some point you may run across this in your console:
Uncaught ReferenceError: WeakMap is not defined

This is because WeakMap is not be compatible with your browser and Babel will not compile it into valid ES5 syntax. An easy work around for this issue is to include this small script into your project:
weakmap.min.js

You must include the weakmap.min.js script before the Hyperform script.

I can not install it using jspm 0.17.0-beta.38

[jspm 0.17.0-beta.38]
After excuting: jspm install npm:hyperform

I got all this

     Updating registry cache...
     Downloading npm:[email protected]

warn npm dependency github:jspm/nodelibs-fs@^0.2.0-alpha uses a @ version which
     is invalid in npm. Use # as the version separator or set "registry": "jspm"
     in the override for the install to work.

warn npm dependency github:jspm/nodelibs-path@^0.2.0-alpha uses a @ version
     which is invalid in npm. Use # as the version separator or set "registry":
     "jspm" in the override for the install to work.

warn npm dependency github:jspm/nodelibs-process@^0.2.0-alpha uses a @ version
     which is invalid in npm. Use # as the version separator or set "registry":
     "jspm" in the override for the install to work.

err  Error on locate for github:core-js
GitHub packages must be of the form owner/repo.

     Peer dependency conflict for fs:
Install the peer fs from npm:[email protected] -> github:jspm/nodelibs-fs@^0.2.0-alpha? [Yes]: 

warn Installation changes not saved.

err  Error locating github:core-js.

Thanks! ;)

Declarative setting of validation rules

Like the declarative nature of providing error messages, it should be possible to set validation rules on inputs declaratively.

jQuery Validation has a data-rule-* format for these, where you can pass settings in to the validation rule in the attribute value, if necessary.

As far as I can see from the code as it is now, you'd have to iterate over all the inputs that need a custom validator and pass them through the addValidator method one by one.

Should we meddle with the locale in toLocaleString() calls?

Example: In src/tools/format_dates.js we call

return (date.toLocaleTimeString || date.toTimeString).call(date);

There we should perhaps add our knowledge of the requested locale from hyperform.setLanguage() calls.

date.toLocaleTimeString(get_current_language())

with get_current_language() to be written in components/localization.js.

FYI: HTML 5.2 API additions and CSS level 4 selectors

HTML 5.2

http://developer.telerik.com/featured/welcome-to-html-5-2/#toc_4

  • The month and week values of the type attribute of the <input> element. As their name suggest, they define controls for setting the element's value to a string representing a month and a week.
  • The forceSpellcheck() method has been added to the HTMLElement interface and allows you, as a developer, to force the user agent to perform a spelling and grammar check on the element it is invoked on, even if the user has not focused it. An example of usage would be inputElement.forceSpellcheck(). Unfortunately, no browsers support it yet.
  • The allowfullscreen attribute is a Boolean attribute for the iframe element and it specifies that the iframe is allowed to be in full screen mode when calling the requestFullScreen() method. If this isn't set, the element can't be in full screen mode.
  • The reportValidity() method, when invoked, forces user agent to validate the constraints of the <form> element. Some examples are to check if a required element has not been filled or if a field respects its pattern attribute. It returns true if the constraint validation returns a positive result or false otherwise. This method is currently supported by Chrome and Opera.

CSS level 4 user pseudos

https://drafts.csswg.org/selectors/#user-pseudos

The :user-invalid pseudo-class represents an element with incorrect input, but only after the user has significantly interacted with it. The :user-error pseudo-class must match an :invalid, :out-of-range, or blank-but-:required elements between the time the user has attempted to submit the form and before the user has interacted again with the form element. User-agents may allow it to match such elements at other times, as would be appropriate for highlighting an error to the user. For example, a UA may choose to have :user-error match an :invalid element once the user has typed some text into it and changed the focus to another element, and to stop matching only after the user has successfully corrected the input.

Not sure if this is user-invalid or user-error.
https://www.w3.org/TR/2013/WD-selectors4-20130502/#user-pseudos

add support for module.exports

or export default hyperform. Right now, dist/hyperform.* can be used globally or as AMD module, but not as CommonJS or ES2015 module. Workaround for ES2015 until fix:

require('hyperform/src/hyperform');

Address mouse events over disabled form fields

This might be an interesting case to address for Hyperform: Try to fix the behaviour mentioned by @jakearchibald, tweet and blog post:

Turns out, mouse events don't fire when the pointer is over disabled form elements, except in Firefox.

and his proposed fix:

input[disabled],
button[disabled] {
  pointer-events: none;
}

This means disabled form elements cannot be interacted with, but it also solves the event issue.

We could implement that in a similar fashion to how we handled the button > span case in d855e6d.

Radios connected by `name` are not linked

There is code in components/renderer, that is basically useless, because it's too late. The re-evaluation of radio buttons with the same name must occur earlier.

npm install fails: TypeError: Cannot read property '0' of undefined

  • Windows 10
  • Node v6.10.0
  • npm v5.3.0
8401 verbose stack TypeError: Cannot read property '0' of undefined
8401 verbose stack     at rmStuff (C:\Program Files\nodejs\node_modules\npm\lib\unbuild.js:61:24)
8401 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
8401 verbose stack     at ret (eval at makeNodePromisifiedEval (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promisify.js:184:12), <anonymous>:13:39)
8401 verbose stack     at lifecycle.then.then (C:\Program Files\nodejs\node_modules\npm\lib\install\action\unbuild.js:12:12)
8401 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
8401 verbose stack     at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
8401 verbose stack     at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
8401 verbose stack     at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
8401 verbose stack     at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
8401 verbose stack     at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)
8401 verbose stack     at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
8401 verbose stack     at Immediate.Async.drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
8401 verbose stack     at runCallback (timers.js:651:20)
8401 verbose stack     at tryOnImmediate (timers.js:624:5)
8401 verbose stack     at processImmediate [as _immediateCallback] (timers.js:596:5)

Question: use hypeform with rollup

I am trying to implement hyperform as ES2015 module with rollup and babel. Though, I am not getting around the 'hyperform' is not exported by node_modules/hyperform/src/hyperform.js error. I have tried the suggestions as stated in the rollup docs.

Has anyone run into this issue as well?

Setting "novalidateOnElements" not respected

The setting "novalidateOnElements" (default true) is not respected (in fact it is never even saved to the settings array).

When checking an element for the non-standard attribute "novalidate", the condition always evaluates to the same boolean value, rendering the attribute "novalidate" ineffective.

see pull request #61

package.json module property reference should not include ES2015+ features

By convention the files referenced by "module" (and the deprecated "jsnext:main") should not contain any ES2015 or newer features outside of import and export. The goal of this property is to allow ES module aware tools like Webpack 2 or Rollup to be able to efficiently consume and optimize package files that are included. Traditionally, packages that are loaded via package.json are not transpiled so leaving other ES2015+ features in those files can cause problems for Hyperform users. See http://2ality.com/2017/04/setting-up-multi-platform-packages.html for more information.

Instead a version of the package should be transpiled with the exception of module features and then referenced from the "module" property in package.json.

Autostart

I suppose, that not many users want to set Hyperforms for particular form, my proposal is to autostart the Hyperform, so at the end of library initialize it with
hyperform(window);
Many of libraries works like that, I think it will be much more easy for many developers.

When `revalidate` is `never`, Firefox takes over validation again

We call form.submit(), when we detect a "submit this form" event (clicking button, enter in text field). This should directly submit the form. Unfortunately, Firefox fires its built-in validation beforehand. (Other browsers: ?) This should be prevented. If the dev says: "revalidate: never", it should really be never.

When submitting, fire a submit event before

When revalidate is never, we submit the form under circumstances. In this case, we ourselves should fire a cancelable submit event. (Preferably normalized for different browser quirks.)

Minlength/maxlength support for textarea elements

I noticed that minlength/maxlength checks don't seem to work for textarea elements. I traced this back to this conditional check in validators/minlength.js: text_types.indexOf(get_type(element)) === -1. This fails as textarea is not in the text array in components/types.js. Not sure if this is oversight or by design... but adding it to that array addresses the issue from what I can tell.

Thanks for your work on this great package!

hyperform doesn't instantiating at form element in IE <=10

In IE <= 10 when i instantiate hyperform at some form element hyperform(myForm) - i getting exception Invalid operand to 'instanceof': Function expected.

The problem is that hyperforms Wrapper function checking condition:

if (form === window || form instanceof window.HTMLDocument) {
    ...
}

instanceof window.HTMLDocument fails because of HTMLDocument is undefined

Adapt error messages for date et al. to skip non-matching items

Example: If a type=date field value exceeds its max value, the error message reads something like:

Please enter a date below Jan 01 2000, 2:00 AM.

The , 2:00 AM part is useless and confusing and should be removed.

Where to look: The error message is compiled using sprintf(), which calls toLocaleString() on a Date object. Unfortunately, sprintf has no knowledge of its surroundings. The fix needs to be placed in src/tools/validity_state_checkers.js at each appropriate place, effectively rendering the date, before it hits sprintf().

If we have done so, check, if we ever use the %l placeholder yet. If not we can remove that from sprintf().

Get references to `window` straight

In the context of iframes are some rough edges when handling the window object. I.e., in MSIE are window.HTMLElement and window.parent.HTMLElement different objects. Or when we try to destroy() an instance, it might be that window already ceased to exist. Lots of edge cases, but we should handle them gracefully.

Will not validate other date formats than YYYY-MM-DD

On an <input type="date"> Hyperform requires a strict YYYY-MM-DD format, while HTML5 accepts to set different patterns (a specific pattern can be set with the pattern="" attribute, but Hyperform seems to ignore this attribute).
From my understanding of Hyperform.js code, I suppose the problem is the if conditions in function string_to_date() (lines 876-928). A solution would be to accept various patterns:

  • YYYY-MM-DD
  • YYYY.MM.DD
  • DD-MM-YYYY
  • DD/MM/YYYY
  • DD.MM.YYYY
  • MM-DD-YYYY
  • etc.

Hyperform does not work with webpack

The "browser" config of hyperform does not export a module, this breaks usage in webpack and possibly other tools (like browserify):

The problem seems to be caused by pointing to the .min.js file in package.json:

   "browser": "dist/hyperform.min.js",

This file that does not export anything and thus lead to empty imports.

Steps to reproduce:

  • Install and configure webpack
  • npm install hyperform
  • import hyperform from 'hyperform'; / var hyperform = require('hyperform');
  • "hyperform" is set to an empty object

Suggested fixes:

1. Point to a file that exports the module:

Changing the problem line in package.json to:

  "browser": "dist/hyperform.cjs.js",

Should resolve the issue as this file seems to export the module properly.

2. Export the module in the minified version:

Adding an export to the minified version should both result in a small and exported version.

Invalid date not detected on Chrome

An invalid date (e.g. 04/31/1998) is not caught but only in a specific situation: using hyperform(document.forms[0]) on a Chrome browser.

If using above code on IE (the only one I've tested so far) or using hyperform(window) on either browser, invalid date is caught and form not submitted.

My test code:

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="dist/hyperform.js"></script>
</head>
<body>
<form id="test">
	<p>A date field:</p>
	<input type="date">
	<input type="submit">
</form>
<script type="text/javascript">
	hyperform(document.forms[0]);
</script>
</body>
</html>

hyperform methods leak implementation

For example, hyperform.set_message returns the internal WeakMap wrapper. The public functions should return the global hyperform again so calls can be chained.

"browser compatibility" missing

would love to see which browsers are fully supported.

IE11 for example, is not supported, in terms of showing a correct timepicker.

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.