Custom HTML5 Form Validation Super Tiny JavaScript Library – ok.js

You must have applied HTML5 form validation before form submitting but you can also made some customisation with default HTML 5 Form validation rules here i am going to share A super tiny JavaScript library for form validation. Ok.js is an very small utility library to validate forms with more than what HTML5 offers you. Features include customized messages and validator chaining.


Libraries

Include plugins minified library on page.

<script src="ok.min.js"></script>

HTML

In sample example design simple html form where we need to apply multiple html5 validation rules.

<form class="form">
            <div class="form-group">
                <label for="exampleInputName">Name (all caps)</label>
                <input type="text" class="form-control" id="exampleInputName" placeholder="Enter Name" required data-ok="nameCaps">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail">Email address (.in only)</label>
                <input type="email" class="form-control" id="exampleInputEmail" placeholder="Enter email" required data-ok="emailIn">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail">Email ID (all caps and ending in .in)</label>
                <input type="email" class="form-control" id="exampleId" placeholder="Enter email" required data-ok="nameCaps, emailIn">
            </div>
            <div class="form-group">
                <label for="exampleInputYear">Year (must be in or after 2019)</label>
                <input type="date" class="form-control" id="exampleInputYear" required data-ok="customDate">
            </div>
            <input type="submit" class="form-control">
        </form>



JS

Create a new OK object and define your own validation rules & custom error messages.

const ok = new Ok({
    nameCaps: {
        msg: "Must be in all caps",
        fn: val => val.toUpperCase() === val
    },
    emailIn: {
        msg: "Must end with '.in'",
        fn: val => /.+\.in$/i.test(val)
    },
    customDate: {
        msg: "Please select a date in or after 2019",
        fn: val => {
            const date = new Date(val);
 
            return date.getFullYear() >= 2019;
        }
    }
});
 
Array.from(document.querySelectorAll("[data-ok]")).forEach(inputElement => {
    ok.bind(inputElement);
});

See live demo and download source code.

DEMO | DOWNLOAD

Visit official github repository for more information and follow for future updates. Don’t forget to read license for using this plugin in your projects.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.