uber-form

0.1.0 • Public • Published

UberForm

Uber form is a library with the purpose of making form submission a breeze. It provides a simple way to validate and submit forms without needing to give up control when you need it. This is achieved with a set of form events, and set of customizable options with sensible defaults. It also integrates with jQuery if available on the page.

<form data-uber-form>
 
  <div data-uber-form-field-group>
    <label for="hello">Hello</label>
    <input type="text" name="hello" id="hello">
    <span data-uber-form-field-errors></span>
  </div>
 
  <div>
    <input type="submit" value="Submit">
  </div>
 
</form>
uberForm.el.addEventListener('uber:validate:hello', function(e) {
  if (uberForm.getFieldElement('hello').value !== 'World') {
    uberForm.setError('hello', 'Must be "World"');
  }
});

Or with jQuery

var $hello = $('#hello');
 
$hello.on('uber:validate', function(e) {
  if ($hello.val() !== 'World') {
    $hello.uberFormSetError('Must be "World"');
  }
});

Creating an Uber Form

There are a few ways to create uber forms; with a form attribute, using the UberForm constructor, and with the uberForm jQuery method.

To create an uber form automatically with simply add the attribute data-uber-form. On DOM ready uberForm will search for form elements with the data-uber-form attribute and automatically initialize and instance of uber form upon the element in question. Note that this behavior can be changed by changing the selector used to search for forms. The selector is set on UberForm.formSelector.

<!-- This form will automatically be setup as an uber form -->
<form data-uber-form>
  ...
</form>

Uber forms can also be initialized manually. This is the recommended way to setup uber forms if you need to set custom options, and you aren't using jQuery. Simply pass the form element you wish to turn into an uber form to the UberForm constructor.

// This will setup a form element as an uber form
var myForm = document.querySelector('#myForm');
var uberForm = new UberForm(myForm, {/* opts */});

If you are using jQuery the same can be achieved as follows.

$('#myForm').uberForm({/* opts */});

Capturing Uber Form Events

One of the main reasons you may wish to use uber form is to handle the validation for your form fields. Uber form has built in validation, however it's extremely easy to add your own to any field.

var secretField = uberForm.getField('secret');
secretField.addEventListener('uber:validate', function(e) {
    if (secretField.value !== 'open sesame') {
        uberForm.setError('secret', 'That\'s not the secret!');
    }
});

Or with jQuery

var $myField = $('#myField');
$myField.on('uber:validate', function() {
    if ($myField.val() !== 'open sesame') {
        $myField.uberFormSetError('That\'s not the secret!');
    }
});

Documentation

All you need to how about the UberForm API is below.

UberForm

Creates a new uber from instance for a given form element. It will also attach itself to the form element as a property called uberForm.

new UberForm(HTMLFormElement el, Object options) => UberForm uberForm
 
// Attaches the instance to the element
el.uberForm => UberForm uberForm
 
options {
  String   bodyFormat              ||= UberForm.bodyFormat
  String   formClass               ||= UberForm.formClass
  String   formErrorClass          ||= UberForm.formErrorClass
  String   fieldGroupErrorClass    ||= UberForm.fieldGroupErrorClass
  String   fieldErrorClass         ||= UberForm.fieldErrorClass
  String   formErrorsSelector      ||= UberForm.formErrorsSelector
  String   fieldGroupSelector      ||= UberForm.fieldGroupSelector
  String   fieldErrorsSelector     ||= UberForm.fieldErrorsSelector
  String   formMethodAttribute     ||= UberForm.formMethodAttribute
  String   formActionAttribute     ||= UberForm.formActionAttribute
  String   formTargetAttribute     ||= UberForm.formTargetAttribute
  String   formNoValidateAttribute ||= UberForm.formNoValidateAttribute
  String   errorsContainerTemplate ||= UberForm.errorsContainerTemplate
  String   errorTemplate           ||= UberForm.errorTemplate
  Function errorFormatter          ||= UberForm.errorFormatter
}

Uber Form Events

Uber form implements a set of events emitted from form elements that have been passed to the UberForm constructor. These events are meant to allow for control over form validation and submission.

'uber:validate'

Fired from uber form elements prior to validation. You may want to check for errors that are dependent on multiple fields here. It is recommended you listen for a specific field with the uber:validate:[fieldName] event instead if you want to check a single field. Calling preventDefault will stop submission, and validation will not complete.

formEl.addEventListener('uber:validate', listener(Event e)) => undefined
 
{
    Function        preventDefault() // Prevents the form from validating
    HTMLFormElement target           // The form element
}
 

'uber:validate:[fieldName]'

Fired from uber form elements prior to validation. This is where you should validate individual fields. Calling preventDefault will stop submission, and validation will not complete. Note that you need to replace [fieldName] with the name of the field you wish to target.

formEl.addEventListener('uber:validate:[fieldName]', listener(Event e)) => undefined
 
{
    Function        preventDefault() // Prevents the form from validating
    HTMLFormElement target           // The form element
}

'uber:validate:*'

Fired from uber form elements prior to validation. This event will fire for every field element that has a name in your uber form. Calling preventDefault will stop submission, and validation will not complete.

formEl.addEventListener('uber:validate:*', listener(Event e)) => undefined
 
{
    Function        preventDefault() // Prevents the form from validating
    HTMLFormElement target           // The form element
}

'uber:submit'

Fired from uber form elements after validation, prior to submission. If you need to block form submission for any reason this is the recommended event to block on. Calling preventDefault will stop submission.

formEl.addEventListener('uber:submit', listener(Event e)) => undefined
 
{
    Function        preventDefault() // Prevents the form from submitting
    HTMLFormElement target           // The form element
}

'uber:submit:[fieldName]'

Fired from uber form elements after validation, prior to submission. If you need to block form submission for any reason, related to a given field, this is the recommended event to block on. Calling preventDefault will stop submission. Note that you need to replace [fieldName] with the name of the field you wish to target.

formEl.addEventListener('uber:submit:[fieldName]', listener(Event e)) => undefined
 
{
    Function        preventDefault() // Prevents the form from submitting
    HTMLFormElement target           // The form element
}

'uber:submit:*'

Fired from uber form elements after validation, prior to submission. If you need to block form submission for any reason, related to one of any of the fields contained, this is the recommended event to block on. Calling preventDefault will stop submission.

formEl.addEventListener('uber:submit:*', listener(Event e)) => undefined
 
{
    Function        preventDefault() // Prevents the form from submitting
    HTMLFormElement target           // The form element
}

'uber:abort'

Indicates form submission was aborted. Fired after either validate or submit events. If e.preventDefault is called during validation then it will fire after validate events have fired. If e.preventDefault is called during submission then it will fire after the submit event

formEl.addEventListener('uber:abort', listener(Event e)) => undefined
 
{
    HTMLFormElement target           // The form element
}

'uber:success'

Fired from uber form elements after the data has been successfully sent to the server.

formEl.addEventListener('uber:success', listener(Event e)) => undefined
 
{
    String          body             // is a string with text responses
    Object          body             // is object if responseType is json
    null            error            // always null in success
    XMLHttpRequest  xhr              // the xhr object used to make the request
    HTMLFormElement target           // The form element
}

'uber:error'

Fired from uber form elements in the event of an error during submission to the server.

formEl.addEventListener('uber:error', listener(Event e)) => undefined
 
{
    String          body             // is a string with text responses
    Object          body             // is object if responseType is json
    Error           error            // an error object describing the error
    XMLHttpRequest  xhr              // the xhr object used to make the request
    HTMLFormElement target           // The form element
}

Uber Form Field Element Events

Field elements within an uber form element also implement a set of events. It is recommended you use the form element events, but these are provided for ease of use.

'uber:validate'

Fired from field elements after validation, prior to submission. Calling preventDefault will stop submission.

fieldEl.addEventListener('uber:validate', listener(Event e)) => undefined
 
{
    Function    preventDefault() // Prevents the form from validating
    HTMLElement target           // The field element
}

'uber:submit'

Fired from field elements after validation, prior to submission. Calling preventDefault will stop submission.

fieldEl.addEventListener('uber:submit', listener(Event e)) => undefined
 
{
    Function    preventDefault() // Prevents the form from submitting
    HTMLElement target           // The field element
}

UberForm.init

Runs automatically upon when the DOM is ready. Crawls the given document or element for all forms matching the given selector. It then creates an UberForm instance for each.

UberForm.init(Document doc,   String formSelector) => undefined
UberForm.init(HTMLElement el, String formSelector) => undefined
 
formSelector ||= UberForm.formSelector

UberForm.bindJQuery

Adds methods to jQuery selections for creating and working with UberForm instances. See 'jQuery Selection Methods' below for documentation.

UberForm.bindJQuery(jQuery $)

UberForm[optionName]

If you wish to change default options they are available on the UberForm constructor. Changing these values with change the defaults for any new UberForm instances created.

String   UberForm.bodyFormat              ||= 'url-encoded'
String   UberForm.formClass               ||= 'uber-form'
String   UberForm.formErrorClass          ||= 'uber-form-error'
String   UberForm.fieldGroupErrorClass    ||= 'uber-form-field-group-error'
String   UberForm.fieldErrorClass         ||= 'uber-form-field-error'
String   UberForm.formSelector            ||= 'form[data-uber-form]'
String   UberForm.formErrorsSelector      ||= '[data-uber-form-errors]'
String   UberForm.fieldGroupSelector      ||= '[data-uber-form-field-group]'
String   UberForm.fieldErrorsSelector     ||= '[data-uber-form-field-errors]'
String   UberForm.formMethodAttribute     ||= 'method'
String   UberForm.formActionAttribute     ||= 'action'
String   UberForm.formTargetAttribute     ||= 'target'
String   UberForm.formNoValidateAttribute ||= 'data-uber-form-novalidate'
String   UberForm.fieldTypeAttribute      ||= 'type'
String   UberForm.errorsContainerTemplate ||= '<div class="uber-form-error-messages">{{errors}}</div>'
String   UberForm.errorTemplate           ||= '<div class="uber-form-error-message">{{errorMessage}}</div>'
Function UberForm.errorFormatter()        ||= function(Array errors) => String errorHTML

UberForm#[optionName]

If you wish to access or modify any options on an UberForm instance they are available directly on the instance itself as properties. Changing these values will directly effect the instance behavior.

String   uberForm.bodyFormat              ||= UberForm.bodyFormat
String   uberForm.formClass               ||= UberForm.formClass
String   uberForm.formErrorClass          ||= UberForm.formErrorClass
String   uberForm.fieldGroupErrorClass    ||= UberForm.fieldGroupErrorClass
String   uberForm.fieldErrorClass         ||= UberForm.fieldErrorClass
String   uberForm.formErrorsSelector      ||= UberForm.formErrorsSelector
String   uberForm.fieldGroupSelector      ||= UberForm.fieldGroupSelector
String   uberForm.fieldErrorsSelector     ||= UberForm.fieldErrorsSelector
String   uberForm.formMethodAttribute     ||= UberForm.formMethodAttribute
String   uberForm.formActionAttribute     ||= UberForm.formActionAttribute
String   uberForm.formTargetAttribute     ||= UberForm.formTargetAttribute
String   uberForm.formNoValidateAttribute ||= UberForm.formNoValidateAttribute
String   uberForm.errorsContainerTemplate ||= UberForm.errorsContainerTemplate
String   uberForm.errorTemplate           ||= UberForm.errorTemplate
Function uberForm.errorFormatter          ||= UberForm.errorFormatter

UberForm#el

If you wish to access the form element the UberForm instance is bound to it is available via the el property. Changing the value of this property is not recommended.

HTMLFormElement uberForm.el

UberForm#submit

Submits the form to the server. If you want to submit your form programmatically you should call this method.

UberForm.submit() => undefined

UberForm#filter

Registers a filter function for modifying data before it's sent to the server.

UberForm.filter(Function fn(Object data)) => undefined

UberForm#removeFilter

Removes a filter function for modifing data before it's sent to the server.

UberForm.removeFilter(Function fn(Object data)) => undefined

UberForm#setError

Applies custom errors to a field by name.

uberForm.setError(String fieldName, String errorMsg) => undefined
uberForm.setError(String fieldName, Error error)     => undefined

UberForm#clearErrors

Clears errors on a specific field, or all errors on the form.

uberForm.clearErrors([String fieldName]) => undefined

UberForm#showErrors

Shows errors for the form.

uberForm.showErrors() => undefined

UberForm#hideErrors

Hides errors for the form.

uberForm.hideErrors() => undefined

UberForm#getFieldElements

Gets a all field elements. Only field elements with a name attribute are included.

uberForm.getFieldElements() => HTMLElement[] fieldElements

UberForm#getFieldElement

Gets a field element by name.

uberForm.getFieldElement(String fieldName) => HTMLElement fieldElement

UberForm#serialize

Serializes the form data, returning it in either as a url-encoded string an object. The format can be 'url-encoded' or 'json'.

uberForm.serialize(String format) => String urlEncodedData
uberForm.serialize(String format) => Object formData

UberForm#toObject, UberForm#toJSON

Returns an object containing the form's data

uberForm.toObject() => Object formData

jQuery Selection Methods

$selection.uberForm

Creates a new or modifies and existing uberForm instance on a form element contained within a jQuery selection.

$selection.uberForm([Object options]) => jQuerySelection $selection
 
options {
  String bodyFormat              ||= UberForm.bodyFormat
  String formClass               ||= UberForm.formClass
  String formErrorClass          ||= UberForm.formErrorClass
  String fieldGroupErrorClass    ||= UberForm.fieldGroupErrorClass
  String fieldErrorClass         ||= UberForm.fieldErrorClass
  String formErrorsSelector      ||= UberForm.formErrorsSelector
  String fieldGroupSelector      ||= UberForm.fieldGroupSelector
  String fieldErrorsSelector     ||= UberForm.fieldErrorsSelector
  String formMethodAttribute     ||= UberForm.formMethodAttribute
  String formActionAttribute     ||= UberForm.formActionAttribute
  String formTargetAttribute     ||= UberForm.formTargetAttribute
  String formNoValidateAttribute ||= UberForm.formNoValidateAttribute
  String fieldTypeAttribute      ||= UberForm.fieldTypeAttribute
}

$selection.uberFormSubmit

Submits the form to the server. You should call this method if you want to submit your form programmatically.

$selection.uberFormSubmit() => jQuerySelection $selection

$selection.uberFormSetError

Sets errors on uber form fields. If called on a selection containing an uber form, a fieldName must be given. If called on a selection containing a field element from within an uber form element, the fieldName can be omitted.

// $selection containing a form element
$selection.uberFormSetError(String fieldName, String errorMsg) => jQuerySelection $selection
$selection.uberFormSetError(String fieldName, Error error)     => jQuerySelection $selection
 
// $selection containing a form field element
$selection.uberFormSetError(Error error) => jQuerySelection $selection

$selection.uberFormClearErrors

Clears errors from uber form fields. If called on a selection containing an uber form, a field name can be passed. If a field name is given then only errors for the that field will be cleared. Otherwise all errors for the form are cleared. If called on a selection containing a field element from within an uber form element, the fieldName can be omitted.

// $selection containing a form element
$selection.uberFormClearErrors(String fieldName) => jQuerySelection $selection
$selection.uberFormClearErrors()                 => jQuerySelection $selection
 
// $selection containing a form field element
$selection.uberFormClearErrors() => jQuerySelection $selection

$selection.uberFormShowErrors

Shows errors on uber form fields. Must be called on a a selection containing a uber form element.

// $selection containing a form element
$selection.uberFormShowErrors() => jQuerySelection $selection

$selection.uberFormHideErrors

Hides errors on uber form fields. Must be called on a a selection containing a uber form element.

// $selection containing a form element
$selection.uberFormHideErrors() => jQuerySelection $selection

$selection.uberFormGetField

Gets a field element from an uber form.

// $selection containing a form element
$selection.uberFormGetField(String fieldName) => jQuerySelection $field

$selection.uberFormGetFields

Gets all field elements from an uber form.

// $selection containing a form element
$selection.uberFormGetFields() => jQuerySelection $fields

$selection.uberFormSerialize

Serializes the form data, returning it in either as a url-encoded string an object. The format can be 'url-encoded' or 'json'.

$selection.uberFormSerialize(String format) => String urlEncodedData
$selection.uberFormSerialize(String format) => Object formData

Readme

Keywords

none

Package Sidebar

Install

npm i uber-form

Weekly Downloads

3

Version

0.1.0

License

MIT

Last publish

Collaborators

  • robertwhurst