1.1.0 • Published 2 years ago

underage-validate v1.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Getting Started

To get a local copy up and running follow these simple example steps.

Installation

Ways to install

  • npm

    ```bash
    npm install underage-validate
    ```
    ```html
    <script type="text/javascript" src="path/to/node_modules/underage-validate/underage-validate.min.js"></script>
    ```
    _**Note:** You cannot `require` UnderageValidate, it is meant for browsers which do not support that feature._
  • CDN from unpkg

    <script type="text/javascript" src="unpkg.com/underage-validate"></script>
  • Download From Releases

    <script type="text/javascript" src="path/to/underage-validate.js"></script>

Usage

Now that you have UnderageValidate installed, here's how to use it in your code.

The Basics

  • const validator = new UnderageValidate({
        errorMessageClass: "error",
        errorMessageContainerClass: "error-message-container",
        errorFieldClass: "error"
    });
    The constructor takes in an object of rules, full list of options below. keyName (default): description noErrorMessages (false): If true, will not show error messages errorMessageClass ("error-message"): CSS class that the error message will be given errorMessageContainerClass ("error-message-container"): The class of each container that will hold the error message staticErrorMessages (false): If true, error messages will all be placed in one static container staticContainerId ("error-message-container"): The ID of the static container noErrorFields (false): If true, will not apply a class to invalid inputs errorFieldClass ("error-field"): CSS class that the invalid input will be given

Adding Fields

Now that we have our rules set, let's put our validator to use Assume we have the following page:

  • <form>
        <div class="error-message-container">
            <input id="required" type="text" value="Required" autocomplete="off">
        </div>
    
        <button id="submit">Submit</button>
    </form>
    form, .error-message-container, .error-message-static-container {
        display: flex;
        flex-direction: column;
    }
    
    .error-message {
        color: red;
    }
    
    .error-field {
        outline: 1px red solid;
    }

    Now, in our javascript file we can call addField(id, rules) to start validating fields in our form

    const form = document.querySelector("form");
    
    const validator = new UnderageValidate() // No rules set, assuming the defaults
    .addField("required", { // You can chain wherever makes sense to
        required: true,
        message: "This field is required!"
    });
    
    form.addEventListener("submit", (event) => {
        event.preventDefault();
    
        validator.validate();
    });

    validate() returns a Boolean, so you may use that value in conjuction with the noErrorMessages and noErrorFields rules to create custom error messages. Or even perform actions if the form is valid.

Field Types

Let's take a look at all the field types in more detail

  • The rules object takes any number of keys needed for a field Unlike the rules object for each UnderageValidate instance, you must explicitly specify a field type for it to take effect, so there are no defaults keyName: description required: Requires the field to not be left blank min: Defines a minimum character count in the field max: Defines a maximum character count in the field minValue: Defines a minimum number value in the field maxValue: Defines a maximum number value in the field email: Validates a field's email using Regex password: Validates a password containing 1 letter, 1 number, 8 characters strongPassword: Validates a password containing 1 lowercase letter, 1 uppercase letter, 1 number, 8 characters securePassword: Validates a password containing 1 lowercase letter, 1 uppercase letter, 1 number, 1 symbol, 10 characters regex: Validates a field using the defined regular expression matching: Given a field's id, checks if the values match message: Sets the text to display for the error message

Full Example

Now let's look at a full example to see every way you can configure your instance of UnderageValidate

  • <div class="error-message-container">
        <input id="required" type="text" value="Required">
    </div>
    <div class="error-message-container">
        <input id="min" type="text" value="Min Chars">
    </div>
    <div class="error-message-container">
        <input id="max" type="text" value="Max Chars">
    </div>
    <div class="error-message-container">
        <input id="min-value" type="text" value="3">
    </div>
    <div class="error-message-container">
        <input id="max-value" type="text" value="10">
    </div>
    <div class="error-message-container">
        <input id="email" type="text" value="email@site.com">
    </div>
    <div class="error-message-container">
        <input id="password" type="password" value="password123">
    </div>
    <div class="error-message-container">
        <input id="strong-password" type="password" value="Password123">
    </div>
    <div class="error-message-container">
        <input id="secure-password" type="password" value="Password123!">
    </div>
    <div class="error-message-container">
        <input id="regex" type="text" value="Regex">
    </div>
    <div class="error-message-container">
        <input id="matching" type="text" value="Password123!">
    </div>
    
    <button id="submit">Submit</button>
    form, .error-message-container, .error-message-static-container {
        display: flex;
        flex-direction: column;
    }
    
    .error-message {
        color: red;
    }
    
    .error-field {
        outline: 1px red solid;
    }
    const form = document.querySelector("form");
    
    const validator = new UnderageValidate({
        noErrorMessages: false,
        errorMessageClass: "error-message",
        errorMessageContainerClass: "error-message-container",
        staticErrorMessages: false,
        staticContainerId: "error-message-static-container",
        noErrorFields: false,
        errorFieldClass: "error-field"
    })
    .addField("required", {
        required: true,
        message: "This field is required!"
    })
    .addField("min", {
        min: 5,
        required: true,
        message: "Minimum of 5 characters!"
    })
    .addField("max", {
        max: 20,
        required: true,
        message: "Maximum of 20 characters!"
    })
    .addField("min-value", {
        minValue: 3,
        required: true,
        message: "Minimum value of 3!"
    })
    .addField("max-value", {
        maxValue: 10,
        required: true,
        message: "Maximum value of 10!"
    })
    .addField("email", {
        email: true,
        required: true,
        message: "Invalid email!"
    })
    .addField("password", {
        password: true,
        required: true,
        message: "Invalid password!"
    })
    .addField("strong-password", {
        strongPassword: true,
        required: true,
        message: "Invalid password!"
    })
    .addField("secure-password", {
        securePassword: true,
        required: true,
        message: "Invalid password!"
    })
    .addField("regex", {
        regex: /[a-zA-Z]/g,
        required: true,
        message: "Must match Regular Expression!"
    })
    .addField("matching", {
        matching: "secure-password",
        required: true,
        message: "Passwords do not match!"
    });
    
    document.querySelectorAll("input").forEach((input) => {
        input.addEventListener("input", (event) => {
            validator.validateField(event.target.id);
        });
    });
    
    form.addEventListener("submit", (event) => {
        event.preventDefault();
    
        validator.validate();
        if(document.getElementById("required").value === "Required") validator.invalidateField("required", "Example!");
    });

All instance methods

Let's look at a list of all methods tou can use on an instance of UnderageValidate

  • method(params) -> Return Type: Description addField(id, rules) -> UnderageValidate: Adds a field to be validated. Note: Since UnderageValidate is not form-specific, you can add fields from any input id on a single page removeField(id) -> UnderageValidate: Removes a field from validation modifyField(id, rules) -> UnderageValidate: Modifies the rules for a field, only replacing the rules passed into the object replaceField(id, rules) -> UnderageValidate: Modifies the rules for a field, replacing the rules passed into the object, all others replaced with the defaults validate() -> Boolean: Validates all fields added, adding error messages and field classes if applicable validateField(id) -> Boolean: Validates the given field added, adding an error message and field class if applicable invalidateField(id, message) -> UnderageValidate: Forces an error message onto the given field, useful for recieving errors from a server getInvalidFields() -> Array[{id, rules}]: Returns an array of all invalid field objects after validation getValidFields() -> Array[{id, rules}]: Returns an array of all valid field objects after validation

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Contact

Andrew Elliott - Discord: @andrewse_#6874 - andrewelliottdev@gmail.com

Project Link: https://github.com/andrewse02/underage-validate

1.1.0

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago