1.0.3 • Published 5 years ago

forma-javascript v1.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
5 years ago

README

A lightweight Javascript Form Library to handle HTML forms and their inputs.

Installation

npm install forma

Also available as download or CDN:

// Referencing downloaded file
<script type='application/javascript' src="path/to/forma@1.0.0.js"></script>

// Or referencing CDN
<script type='application/javascript' src="https://www.tools.rjdesignmanagement.ch/forma/downloads/forma@1.0.0.js"></script>

If you are planning on using Forma's LightBox, then make sure to add the Forma CSS:

// Referencing downloaded file
<script type='application/javascript' src="path/to/forma@1.0.0.css"></script>

// Or referencing CDN
<script type='application/javascript' src="https://tools.rjdesignmanagement.ch/forma/downloads/forma@1.0.0.css"></script>

Usage

Setup

<form id="someForm" class="forma" action="/request/path/or/file.php">

    <label class="forma-label">Some input
    
        <input name="my-email-input"
               type="email">

    </label>
    
    <label class="forma-label">Some input
        
        <input name="myPasswordInput"
               data-forma-strict-password
               type="password">
    
    </label>
    
    <!-- some more inputs here... -->

</form>

Basic Usage

let myForma = new Forma('#someForm'); // any selector possible

myForma.onServerSubmit({
    lightbox: true,
    
    // more settings here ...
    
    validation: true
});

// or

myForma.onSubmit((data, event) => {
    
    // Do something here on submit 
    // (no request sent to server)
    
});

Accessing Form Elements

Forma makes it easier to access your inputs directly by references them with their name tag.

// references name tag
let passwordInput = myForma.inputs.myPasswordInput;

// or
let emailInput = myForma.inputs['my-email-input'];

If an input (or textarea) doesn't have a name it will be accessible as myForma.inputs.noName[<index>].

Forma Properties

PropertyDescription
actionGet the action attribute of the <form> element. It is mainly used to set the default path of the form submission.
formatypeCollection of all data-formatype attributes that are set in the <form> element. If you for instance had an element in your <form> with data-formatype="foo" , you could access it like this: myForm.formatype["foo"] . Otherwise it will be accessible like this: myForm.formatype.noName .
inputsCollection of all <input> elements in the <form> . If the inputs have a name tag with a valid name (such as foo ), you can access any specific input like this: myForm.inputs["foo"] . Otherwise the input will be accessable like this: myForm.inputs.noName .
optionsCollection of all <option> elements in the <form> . If the options have a name tag with a valid name (such as foo ), you can access any specific option like this: myForm.options["foo"] . Otherwise the option will be accessable like this: myForm.options.noName .
radiosCollection of all <input type="radio"> elements in the <form> . If the radios have a name tag with a valid name (such as foo ), you can access any specific radio like this: myForm.radios["foo"] . Otherwise the radio will be accessable like this: myForm.radios.noName .
selectsCollection of all <select> elements in the <form> . If the selects have a name tag with a valid name (such as foo ), you can access any specific select like this: myForm.selects["foo"] . Otherwise the select will be accessable like this: myForm.selects.noName .
typesCollection of all <input> elements in the <form> sorted by type .
setupAccepts an object with settings (see chapter Settings). For example: this.setup = { lightbox: true, path: /foobar }

Forma Methods

MethodDescription
showSubmitButton(show)show : true , false
onServerSubmit(settings)Registers an EventListener to the form and sends the form request to the server with custom settings on form submitsettings : see chapter Settings for all possible settings (must be given as an object)
onSubmit(callback)Listens to form submission and executes the given callback function.
reset()Resets the <form> to it's default state (does not effect the Forma settings, only HTML)
selectedOption(selectionName)Returns the selected <option> in the <form> , where the parent (<select>) has the given name attribute.
selectedRadio(radioName)Returns the selected <input type="radio"> with the given name attribute.
unselectedOptions(selectionName)Returns the unselected <option> elements, where the parent (select) has the given name attribute.
unselectedRadios(radioName)Returns the unselected <input type="radio"> elements with the given name attribute.

Settings

SettingDescription
baseURLBase URL of the current server. Retracted from window.location.origin if nothing else is set.
beforeCallback for any custom actions that should be executed before submitting the form.
buttonHide0 : Default setting, submit button is left alone on submit 1 : Hides the submit button on submit (shows after submit) 2 : Hides the submit button on submit (keeps it hidden)
dataData that should be send to the server when form is submitted. As default it takes the data from the form (FormData).
errorCallback for any custom actions that should be executed if an error occurs after submitting the form to the server.
finallyCallback for any custom actions that should always be executed after submitting the form to the server.
formaActiveClassIf you use custom classes to define if an element is visible or not, you can define that class here. It will then be toggled everytime an element needs to be visible.
globalMessageDisplayTimeThe amount of milliseconds before the global message is hidden after being shown (only works if messageBox = 'global'). Default 5000
headersHTTP headers that should be sent along with the form submit.
jmodetrue , then default settings are overriden and the jmode preset is used (see chapter jmode)
lightboxIf this setting is set to true , then Forma creates a lightbox that is toggled whenever you submit the form.
lightboxSourceSet your own spinner by passing the reference to the spinner image as a String (e.g. "/assets/png/spinner.png"). Default: undefined (with own spinner).
loadingGIFYou can pass a query selector to locate your custom loading GIF in the DOM. The loading GIF is then toggled when the form is submitted. Is ignored if loadingGIF not found are setting is set to false.
messageBoxfalse : default, server response ignored"global" : server response shown in global divselector : server response shown in custom divOnly the first response message is displayed in global div.
messageDisplayTimeThe amount of milliseconds the message box (see messageBox) should be displayed, before being hidden again. If 0 or false it will stay unhidden.
methodpost : defaultupdate : sends an update request instead of postpath : sends a path request instead of post
pathYou can define the path that the form should submit to here. Otherwise Forma looks for the path in the action attribute of the <form> . If Forma can't find any path it will submit to the base url.
reloadOnErrortrue if the page should reload on error.
reloadOnFinallytrue if the page should reload on finally.
reloadOnSuccesstrue if the page should reload on success.
successCallback for any custom actions that should be executed after submitting the form to the server, if no errors occured.
timeoutNumber of milliseconds before the request times out. Default: 20000
trashtrue if you want specific inputs to have a trash can to easily clear the input. The inputs need to be wrapped in the <label> tags to make it work properly. To enable it on your inputs add data-forma-trash to each of them. Only works on the following input types: email, password, search, tel, text, url, and also all <textarea> tags.
trashPosition: { bottom: "10px", left: "10px", right: false, top: "calc(50% - 4px)", zIndex: 10000}Pass an object to trashPosition with the properties bottom, left, right, top, zIndex. Default: all properties false
validationtrue if you want real-time validation on your input forms. You can then add attributes such as maxLength="5" to any input or data-forma-mixed-cases to your type="password" input. See chapter Validation for more.

JMode

JMode is a setting that defines some settings as a preset. These settings were defined by R. J. Design Management and are listed here:

{
    baseURL: window.location.origin,
    before: () => {},
    buttonHide: 2,
    data: undefined,
    error: () => {},
    finally: () => {},
    formaActiveClass: '.active',
    globalMessageDisplayTime: 5000,
    headers: {},
    jmode: true,
    lightbox: false,
    loadingGIF: '.loadinggif',
    messageBox: '.formsuccess',
    messageDisplayTime: 0,
    method: 'post',
    path: form.action || '',
    reloadOnError: false,
    reloadOnFinally: false,
    reloadOnSuccess: false,
    success: () => {},
    timeout: 20000,
    trash: false,
    trashRight: false,
    trashTop: false,
    validation: false
}

To switch jmode on just enable it in the onServerSubmit(settings) like this:

myForma.onServerSubmit({
    jmode: true
});

Validation

Forma offers a more extensive real-time client-side validation than the HTML5 standard. To enable the validation just set the validation setting to true in the onServerSubmit(settings), like this:

myForma.onServerSubmit({
    validation: true
});

To make it work though you need to let Forma know which inputs need to be validated. In the next part, we will explain how this is done.

Inputs / Textareas

All inputs and textareas can add the following attributes to enable the real-time validation:

AttributeDescription
maxLengthMaximum amount of characters allowed
minLengthMinimum amount of characters allowed
requiredInputs that are required for correct submission of form

Email

If the validation setting is set to true then Forma automatically validates all email inputs.

Password Inputs

Password inputs have more attributes that are listed below:

AttributeDescription
data-forma-mixed-charactersChecks if password has at least 1 normal and 1 special character ($, @, %, ...)
data-forma-mixed-casesChecks if password has lower- and uppercase characters
data-forma-strict-passwordEnables all of the listed attributes here (instead of listing all the attributes separatly)
data-forma-with-numberChecks if password has at least 1 number

All other validation attributes that were listed in the beginning of this chapter also apply to the password input.

<label>Some password

    <input type="password" data-forma-strict-password required>
        
</label>

Trash

The trash setting allows you to put a trash can in some of the inputs so that they can be cleared easily. The following inputs are supported:

  • email
  • password
  • search
  • tel
  • text
  • url
  • textarea

To make this work you need to enable the trash setting in the onServerSubmit(settings) method like this:

myForma.onServerSubmit({
    trash: true
});

Then you need to add the data-forma-trash attribute to the inputs you want to be affected.

<label>Some password

    <input type="password" data-forma-trash>
        
</label>
1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago