1.2.0 • Published 11 days ago

@egodesign/form v1.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
11 days ago

@egodesign/form

A Javascript class to fully validate and send forms.

Usage:

Import the EgoForm class into your file and then create as many instances as needed.

import EgoForm from '@egodesign/form';

const myForm = new EgoForm({
    element: document.getElementById('myForm'),
    submitType: 'fetch',
    debug: true,
    submitDataFormat: 'formData',
    requestHeaders: {},
    fieldGroups: {
        phone_numbers: [
            'phone',
            'mobile'
        ]
    },
    serializerIgnoreList: ['ignore'],
    classes: {
        requiredField: '--required',
        requiredIfFilledField: '--required-if-filled',
        fieldHasError: '--has-error',
        controlHasError: 'is-danger',
        hiddenErrorMessage: 'is-hidden',
        formSubmittingState: '--submitting',
        buttonSubmittingState: 'is-loading'
    },
    customValidations: {
        test: [{
            name: 'isValid',
            condition: (value) => value === 'testing',
            message: 'This field value should be "testing".'
        }]
    },
    customValidationsMessages: {
        "fieldName": {
            "empty": "message",
            "invalid": "message",
        }
    },
    onStepChange: (previous, next) => console.log(current, next),
    onBeforeSubmit: () => console.log('Before submit'),
    onValidationError: fields => console.log(fields),
    onSubmitStart: () => console.log('Submit start'),
    onSubmitEnd: () => console.log('Submit end'),
    onSuccess: resp => console.log('Success', resp),
    onError: err => console.log('Error', err)
});

HTML structure sample:

<form method="GET" action="https://jsonplaceholder.typicode.com/todos/1" id="myForm" novalidate>
    <div class="form__field --required" data-type="text">
        <label for="nameInput">Name</label>
        <input class="form__control" 
            type="text" 
            name="name" 
            id="nameInput" 
            placeholder="Text input"
            aria-invalid="false" 
            aria-errormessage="nameInputError"
            required>
            <p class="form__error" id="nameInputError"></p>
    </div>
    
    <div class="form__field --required" data-type="email">
        <label for="emailInput">Email</label>
        <input class="form__control" 
            type="email" 
            name="email" 
            id="emailInput" 
            placeholder="Email input"
            aria-invalid="false" 
            aria-errormessage="emailInputError"
            required>
        <p class="form__error" id="emailInputError"></p>
    </div>

    <div class="form__field" data-type="file" data-max-size="15">
        <label for="fileInput">File upload</label>
        <small>Max. file size 2MB</small>
        <input class="file-input form__control" 
            type="file" 
            name="resume"
            id="fileInput" 
            aria-invalid="false" 
            aria-errormessage="fileInputError">
        <p class="form__error" id="fileInputError"></p>
    </div>
    
    <div class="form__field" data-type="text">
        <label>Message</label>
        <textarea class="form__control" 
            name="message" 
            placeholder="Textarea"
            aria-errormessage="msgTextError">
        </textarea>
        <p class="form__error" id="msgTextError"></p>
    </div>
    
    <button type="submit">Submit</button>
</form>

Required Classes

ClassDescription
form__fieldThis is the element that wraps the label, the control and the error message of a specific field.
form__controlThis is a control element. It could be either an input, a select, a textarea, etc.
form__errorThis is the element which will be used to display error messages for a specific field.

Customizable Classes

NameDefaultDescription
requiredField--requiredUse this class to mark required fields.
requiredIfFilledField--required-if-filledUse this class to mark those fields that should be validated only when filled. For example, an email field that is not required but should be a valid email if filled.
fieldHasError--has-errorThis class is added to the fields that has errors after validation and removed when the field is focused.
controlHasError-You can set this class to be added to the controls that has errors. Works similar to fieldHasError.
hiddenErrorMessage--hiddenThis class is removed from the error messages when it's parent field has errors and added back when the field is focused.
formSubmittingState--submittingThis class is added to the form while it's being submited.
buttonSubmittingState--loadingThis class is added to the submit button while the form is being submited.

Options

NameDescriptionAccepted values
elementThe form element. I.g. document.getElementById('myform')A DOM element
submitTypeThe method that will be used to submit the form. IMPORTANT: the action attribute is required in any case.fetch, get and post
submitDataFormatIf submitTypes is fetch, this option will be use to define de content type of the request.json and formData
requestHeadersIf submitTypes is fetch, this option lets you pass your own headers. Should recieve an object containing valid HTTP headers. See reference.Object or null.
fieldGroupsGroup fields as nestes objects inside the body of the request. Should recieve an object containing key-value pairs, where the key is the name of the group and the value an array listing the field names.Object or null.
classesCustomize some classes to match your own. Should recieve an object containig the replaced classnames. See customizable classesObject or null.
customValidationsDefine your own validations. Should recieve an object containig key-value pairs, where the key is the name of the custom data-type, and the value an array of validations defining a condition to be passed and a message in case it's not.Object or null.
customValidationMessagesLets you customize existing validation messages. It expects an object containing the name of the field and the custom messages inside. Refer to Usage to see an example.Object or null.
resetOnSuccessThis option completely resets the form and its fields.Boolean, default true.
scrollOnErrorThis option smoothly scrolls the page to show the first field with errors. Useful when building long forms to make sure the user sees the errors.Boolean, default true.
debugOn debug mode, the form won't be submitted. Intead, every step will be logged into the dev console of the browser.Boolean, default false.

Events

NameDescriptionAccepted values
onStepChangeEvent triggered every time there's a step change. Only available for stepped forms. It returns the previous and the next steps.An anonymous function or null.
onValidationErrorEvent triggered when there's any validation error. It returns an array containing the names of the invalid fields.An anonymous function or null.
onBeforeSubmitEvent triggered before the submit starts.An anonymous function or null.
onSubmitStartEvent triggered when the submit starts.An anonymous function or null.
onSubmitEndEvent triggered when the submit ends, regardless of the outcome.An anonymous function or null.
onSuccessEvent triggered when the request results successful.An anonymous function or null.
onErrorEvent triggered when the response returns an error.An anonymous function or null.

Validation:

In order to use validations, you must set the correct data type for each field. You can do so by adding a type data attribute to the field element, e.g; <div class="form__field" data-type="text">. This attribute will be used by the validator to run certain tests. Here's a list of the different available data types: | Name | Description | | ---| --- | | text | This can be considered as the default type. It's use for simple text input and it doesn't have any special validation appart from the required ones. | | email | Used for email inputs. It validates the value to comply the requirement for a well formed email address. | | url | Used for URL inputs. It validates the value to comply the requirement for a well formed URL. | | cuit / cuil | It validates the value to comply the requirement for a valid CUIT or CUIL number, applying the official formula. | | password_repeat | Use this type alogn with a password field whit an ID of password, to validate that both fields have the same value. Mostly intended for password reset forms. | | single_checkbox | This type validates that a specific checkbox is checked. Useful for cases like terms and conditions acceptance. |

Masks:

Add this class names to the field element in oprder to apply some masks and filters to your inputs.

Class nameDescriptionExtra attributes
--numberIt converts the value to only numbers, with the option of being formated and support decimals.data-thousands-separator: if declared it will be used to separate thousands.data-decimal-separator: if declared it will be used to separate decimals.data-decimals: the number of decimal places, defaults to 2.
--money-amountIt converts the input into a valid currency expression.data-currency: this attribute is use to mask the field value adding the currency at the begining. Defualts to '$'.
--phoneIt filters the value using a (opinionated) regular expression, which only allows numbers, plus symbols, hyphens, parentheses and white spaces.

Extras

Toggle password visibility

Add a button with the class name form__toggle-password-visibility inside the field element to toggle the control (input) type between password and text. Note: the control and the button must be siblings.

1.2.0

11 days ago

1.1.6

3 months ago

1.1.1

9 months ago

1.1.0

9 months ago

1.1.5

7 months ago

1.1.4

9 months ago

1.0.5

10 months ago

1.1.3

9 months ago

1.1.2

9 months ago

1.0.1

1 year ago