Skip to content

Instantly share code, notes, and snippets.

@eric1234
Last active June 30, 2017 06:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eric1234/4237367 to your computer and use it in GitHub Desktop.
Save eric1234/4237367 to your computer and use it in GitHub Desktop.
Polyfill for HTML5 required attribute

Purpose

Polyfill to provide support for the HTML5 "required" attribute on older browsers.

Does not provide a fancy interface like many browsers. Just a simple popup to let the user know the form is not ready. If users want a nicer interface they should use a nicer browser. :)

Usage

Just compile and include on page. Then use the "required" attribute as if everybody is running a modern browser. You must place the include at the bottom of the page so the form elements will already be in the DOM.

Compile Notes

When compiling the "bare" option should be disabled. This is usually the default but always check. For example the CoffeeScript website's in-browser compiler has "bare" enabled. If "bare" is enabled the script will still work but it will pollute your namespace.

Browser Compatibility

  • Is a no-op for browsers that already support the "required" attribute.
  • Requires no external libraries (i.e. Prototype, jQuery, etc.)
  • Does not use any advanced features (like querySelectAll) for max compatibility.
unless 'required' of document.createElement 'input'
# Cross browser event handling
addEvent = (element, event, callback) ->
if addEventListener?
element.addEventListener event, callback, false
else
element.attachEvent "on#{event}", callback
cancelEvent = (event) ->
if event.preventDefault
event.preventDefault()
else
event.returnValue = false
# Form processing
value = (field) ->
switch field.tagName.toLowerCase()
when 'input', 'textarea'
type = field.getAttribute 'type'
if type == 'checkbox' || type == 'radio'
field.value if field.checked
else
field.value
when 'select'
for option in field.getElementsByTagName 'option'
val = option.getAttribute 'value'
val = option.innerHTML unless val?
return val if option.selected
for form in document.getElementsByTagName 'form'
addEvent form, 'submit', (event) ->
for tag in ['input', 'select', 'textarea']
for field in document.getElementsByTagName tag
continue if field.getAttribute('required') == null
val = value field
continue unless !val || /^\s*$/.test(val)
alert 'Please provide all required fields'
cancelEvent event
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment