GithubHelp home page GithubHelp logo

yaireo / validator Goto Github PK

View Code? Open in Web Editor NEW
258.0 20.0 86.0 160 KB

HTML form validation. Perfectly made for all scenerios, lightweight, semantic & easy to use

CSS 16.99% JavaScript 61.43% HTML 21.58%
form-validation html

validator's Introduction

Validator - Lightweight & Easy HTML form inputs checker

The Validator is cross-browser and will give you the power to use future-proof input types such as:
tel, email, number, date, time, checkbox and url.

npm i @yaireo/validator --save

// usage:

import FormValidator from '@yaireo/validator'

// or download the `validator.js` file and add load it inside your HTML file
<script src='validator.js'></script>

Why should you use this?

  • Cross browser validation
  • Deals with all sorts of edge cases
  • Utilize new HTML5 types for unsupported browsers
  • Flexible error messaging system
  • Light-weight (19kb + comments, unminified)

Validation types support

HTML5 offers a wide selection of input types. I saw no need to support them all, for example, a checkbox should not be validated as ‘required’ because why wouldn’t it be checked in the first place when the form is rendered?

For a full list of all the available types, visit the working draft page. These input types can be validated by the JS for – <input type='foo' name='bar' />. (Support is synthesized)

✔️ text
✔️ email
✔️ password - also comparing "re-type password" inputs
✔️ number
✔️ date
✔️ time
✔️ uRL
✔️ search
✔️ file
✔️ tel
✔️ checkbox
✔️ select
✔️ textarea
✔️ hidden – can also have the ‘required’ attribute

Basic semantics

<form action="" method="post" novalidate>
    <fieldset>
        <div class="field">
            <label>
                <span>Name</span>
                <input data-validate-length-range="6" data-validate-words="2" name="name" placeholder="ex. John f. Kennedy" required="required" type="text" />
            </label>
            <div class='tooltip help'>
                <span>?</span>
                <div class='content'>
                    <b></b>
                    <p>Name must be at least 2 words</p>
                </div>
            </div>
        </div>
        <div class="field">
            <label>
                <span>email</span>
                <input name="email" required="required" type="email" />
            </label>
        </div>
            ...

First, obviously, there is a Form element with the novalidate attribute to make sure all the native HTML5 validations (which currently suck) are disabled. Proceeding, there is a Fieldset element which is not a must, but acts as a “binding” box for a group of fields that are under the same “category”. For bigger forms there are many field groups that are visually separated from each other for example. Now, we treat every form field element the user interacts with, whatsoever, as a “field”, and therefor these “fields” will be wrapped with <div class='field'>. This isolation gives great powers. Next, inside a field, there will typically be an input or select or something of the sort, so they are put inside a <label> element, to get rid of the (annoying) 'For' attribute, on the label (which also requires us to give an ID to the form field element), and now when a user clicks on the label, the field will get focused. Great. Going back to the label’s text itself, we wrap it with a <span> to have control over it’s style.

The whole approach here is to define each form field (input, select, whatever) as much as possible with HTML5 attributes and also with custom attributes.

HTML Attributes on form elements

Attribute Purpose
required Defines that this field should be validated (with JS by my implementation and not via native HTML5 browser defaults)
placeholder Writes some placeholder text which usually describes the fields with some example input (not supported in IE8 and below)
pattern Defines a pattern which the field is evaluated with. Out-of-the-box available values are:
numeric - Allow only numbers
alphanumeric - Allow only numbers or letters. No special language characters
phone - Allow only numbers, spaces or dashes.

Alternatively, you may write your own custom regex here as well
data-validate-words Defines the minimum amount of words for this field
data-validate-length Defines the length allowed for the field (after trim). Example value: 7,11 (field can only have 7 or 11 characters). you can add how many allowed lengths you wish
data-validate-length-range Defines the minimum and/or maximum number of chars in the field (after trim). value can be 4,8 for example, or just 4 to set minimum chars only
data-validate-linked Defines the field which the current field value (the attribute is set on) should be compared to. Value can be a selector or another input's name attribute's value
data-validate-minmax For type number only. Defines the minimum and/or maximum value that can be in that field
data-validate-text-invalid Error text message for specific field

pattern attribute

It is possible to write your own unique Regex patterns directly in the attribute or reference to it by custom name, for example:

<input type="text" required="required" pattern="myCustomRegex" />
var validator = new FormValidator({
    regex : {
        myCustomRegex: '/whatever/'
    }
}, );

Optional fields

There is also support for optional fields, which are not validated, unless they have a value. The support for this feature is done by adding a class optional to a form element. Note that this should not be done along side the “required” attribute.

Error messages

{
    invalid         : 'input is not as expected',
    short           : 'input is too short',
    long            : 'input is too long',
    checked         : 'must be checked',
    empty           : 'please put something here',
    select          : 'Please select an option',
    number_min      : 'too low',
    number_max      : 'too high',
    url             : 'invalid URL',
    number          : 'not a number',
    email           : 'email address is invalid',
    email_repeat    : 'emails do not match',
    date            : 'invalid date',
    time            : 'invalid time',
    password_repeat : 'passwords do not match',
    no_match        : 'no match',
    complete        : 'input is not complete'
}

This object can be extended easily. The idea is to extend it with new keys which represent the name (attribute) of the field you want the message to be linked to, and that custom message appear as the general error one. Default messages can be over-ridden.

Example of a specific input field's error message:

<input type="text" data-validate-length-range="2,6" required="required" pattern="alphanumeric"  data-validate-text-invalid='Please follow the pattern rules'/>

Another example:

<input type="text" name="mySpecialInput" data-validate-length-range="2,6" required="required" pattern="alphanumeric" />
var validator = new FormValidator({
    texts : {
        mySpecialInput: 'wrong input' // set custom error message for that specific field, by "name"
    }
});

Example: for a given type date field, lets set a custom (general error) message like so:

// set custom text on initialization:
var validator = new FormValidator({
    texts : {
        date: 'not a real date'
    }
});

// or post-initialization
var validator = new FormValidator();
validator.texts.date = 'not a real date';

Error messages can be disabled:

    validator = new FormValidator({
        alerts: false
    });

    // or by:
    var validator = new FormValidator();
    validator.settings.alerts = false;

Binding the validation to a form

There are two ways to validate form fields, one is on the submit event of the form itself, then all the fields are evaluated one by one. The other method is by binding the checkField function itself to each field, for events like Blur, Change or whatever event you wish (I prefer on Blur).

Usage example - validate on submit

A generic callback function to have the form validated on the Submit event. You can also include your own personal validations before the checkAll() call.

var validator = new FormValidator();
// select your "form" element from the DOM and attach an "onsubmit" event handler to it:
document.forms[0].onsubmit = function(e){
    var validatorResult = validator.checkAll(this); // "this" reffers to the currently submitetd form element

    return !!validatorResult.valid;
};

Usage example - validate on field blur/input/change events

Check every field (using event Capture)

var validator = new FormValidator();

document.forms[0].addEventListener('blur', function(e){
    validator.checkField(e.target)
}, true);

document.forms[0].addEventListener('input', function(e){
    validator.checkField(e.target);
}, true);

document.forms[0].addEventListener('change', function(e){
    validator.checkField(e.target)
}, true);

Utilize the internal events' binding system; pass in the settings the events property and assign it an array which states which events should be inputs be validated for. For a single events, a string may be paassed instead of an Array:

var validator = new FormValidator( document.forms[0], {
    "events" : ['blur', 'input', 'change'] // for a single one, just pass a string, ex: "blur"
});

In case the form is not yet ready, the events maybe be binded later, when the form is ready, using the internal events method for a validator instance:

// validate fields on these events:

var validator = new FormValidator(document.forms[0]); // the "<form>" element should be passed when the instance is created or passed to the "events" method below (as the 2nd parameter)

// wait for the form, or its' fields, to be ready (for whatever reason), and then bind the events as follows:
validator.events(['blur', 'input', 'change']);

Tooltips (for each field which did not validate)

The helper tooltips <div class='tooltip help'>, which work using pure CSS, are elements which hold a small '?' icon and when hovered over with the mouse, reveal a text explaining what the field “field” is about or for example, what the allowed input format is.

Classes

validator.settings.classes object can be modified:

var validatorClasses = {
    field : 'field', // class for each input wrapper
    alert : 'alert', // call on the alert tooltip
    bad   : 'bad'    // classes for bad input
};

validator = new FormValidator(null, {classes:validatorClasses});

// or
validator = new FormValidator();
validator.settings.classes.bad = 'error';

Bonus – multifields

I have a cool feature I wrote which I call "multifields". These are fields which are often used to input a credit card or a serial number, and are actually a bunch of input fields which are “connected” to each other, and treated as one. You can see it in the demo page, and it’s included in the ‘multifield.js’ file.

validator's People

Contributors

iamgideonidoko avatar khrees2412 avatar peterblazejewicz avatar yaireo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validator's Issues

where to insert remote ajax call

my js is not strong so plz excuse my density

All is working fine but at what pint would we insert a final "form valid > onSubmit" ajax request to write data?

I hope the answer is simple

Custom validation

Is it possible to integrate my custom validation function to your validator?

I have two inputs:

<input type="email" id="email" name="email" class="rodo_group">
<input type="tel" id="phone_number" name="phone_number" class="rodo_group">

I want to check if my form has certain class. If so I want to check if at least one of these inputs are complete and show custom message in case of error.

Something like require_from_group method in jqueryvalidation plugin. https://jqueryvalidation.org/require_from_group-method/

data-validate-words can't work with other attribute like data-validate-length

When data-validate-words judgment is passed, no other judgment will be made. So if we define multiple attributes that contain data-validate-words, then others will take no effect.

if( data.validateWords ){
    ...
   return true;
}
...

Above is a fragment of the code.

Beside in READEME.md, Classes section

var validatorClasses = {
    //should change to 
    //item: 'field'
    field : 'field', // class for each input wrapper
    alert : 'alert', // call on the alert tooltip
    bad   : 'bad'    // classes for bad input
};
//should change to 
//validator = new FormValidator({classes:validatorClasses}, null);
validator = new FormValidator(null, {classes:validatorClasses});

How to validate both required and email pattern in the same form?

I probably didn't understand well how things work but, how can i validade both required inputs and email? In my app email is required in some forms but not in others. I'm using:

$('#form').on('blur', 'input[required]', validator.checkField);
$('#form').on('blur', 'email', validator.checkField);

But only got email's warnings(invalid email) when the input is required, like a OR operator and i want it to work like a AND.

no checkboxes

Hi, nice little plugin. Just wondering if you could include checkboxes. I did have a poke around in the code trying to get them to work but couldn't. Just about every form I build has a terms and conditions checkbox which is important to validate.
Thanks,
Dave

Ajax validation

Is there a builtin way to validate a field based on ajax call to server. For example I need to validate slug field that it does not already exists.
Second if I manually do a ajax call to server, how can I generate a validation error and show a msg accordingly?

Unique text or email

Is there any way to check that the email is unique or not?
A way to check the value via ajax call.

doesn't validate hidden fields

jquery by default will only validate visible fields but i do have a form which is divided in four tabs but the validation works for the active tabs only.Is there a way to validate all the elements in all tabs?

checkField method return {} for skipped field

On line 411 the validator returns {} when it should return { valid:true, error:"" }, right?

// if field did not pass filtering or is simply not passed
if( !field )
    return { valid:true, error:"" }

Validate fields over multiple tabs under single form

How I tried using version 3.3.1. While it works good under single tab, fields under other tabs (created using bootstrap tabs) are not validated.

Do you have any working example for same? or code fix is required for the same?

thanks in advance

Prevent Submit of the Form

Hi! Such a cool validator!
Im wondering if it is possible to prevent the submitting of the form by default?

I want the validation but have another code which submits the form,
Thanks!
Great work!

onsubmit - var submit = true??

Thanks for your reply but sorry I wasn't quick enough before you closed it. I am southern hemisphere so big time diff.

Yes, I tested that - put in an alert e.preventDefault(); var submit = true; alert('ajax'); - but clearly fields had not been finalised, ie. there were still form errors.

I guess there are two questions:
1 - is it possible to do remote checking - eg. "email in use" - as each field is tested
2 - submitting complete, validated form data - with ajax to retain page state.

Lenght Range

data-validate-lengthRange (like the example) doesn't work, I am trying to get the minimum value. I've tried also data-validate-length-range as suggested in documentation but It doesn't work neither.
What about this mismatch? Which Should I use? Other suggestions? Thanks in advance

Patterns

Is it possible for a pattern to be made specifically for letters and numbers, without accepting any other characters-symbol??

Validate with multiple submit button

Validator seems to be not working when a form has multiple buttons. The buttons' value is not being posted to server.

<input id="userName" name="userName"  readonly="readonly" required="required" type="text"/>
..
<button type="submit" class="btn btn-primary" name="action" value="cancel">Cancel</button>
<button type="submit" class="btn btn-success" name="action" value="submit">Submit</button>
<button type="submit" class="btn btn-danger" name="action" value="delete">Delete</button>

When I click any of the buttons, action value is not being posted as a request parameter, but other input values are (e.g. userName). But when I remove the validation, button action is being posted..

This is how the validator is initialized

function init_validator() {

    if (typeof (validator) === 'undefined') {
        return;
    }
    console.log('init_validator');

    // initialize the validator function
    validator.message.date = 'not a real date';

    // validate a field on "blur" event, a 'select' on 'change' event & a '.reuired' classed multifield on 'keyup':
    $('form')
        .on('blur', 'input[required], input.optional, select.required', validator.checkField)
        .on('change', 'select.required', validator.checkField)
        .on('keypress', 'input[required][pattern]', validator.keypress);

    $('.multi.required').on('keyup blur', 'input', function () {
        validator.checkField.apply($(this).siblings().last()[0]);
    });

    $('form').submit(function (e) {
        e.preventDefault();
        var submit = true;

        // evaluate the form using generic validaing
        if (!validator.checkAll($(this))) {
            submit = false;
        }

        if (submit)
            this.submit();

        return false;
    });

};

Could you please tell me what I am doing wrong?

alphanumeric pattern blocks field changes

Hi,

I may be wrong, but as much as I've tested adding pattern="alphanumeric" forces the pattern test correctly, but once I get error msg (even if for min/max check) I cannot change the field in browser anymore (at least using IE 10)

Here is code snippet I've tested with:

<tr>
<td>Local code</td>
<td>
    <div class="item">
        <div class="tooltip help">
            <label>
                <input name="local_exp" type="text" class="input-normal" id="local_exp" data-validate-length-range="2,6" required="required" placeholder="eg. 123456"  pattern="alphanumeric" />
            </label>
            <div class='content'>
                <p>Required field. Min. 2 chars. Max. 6 chars. Alphanumeric only.</p>
            </div>
        </div>
    </div>
</td>
</tr>

If I remove pattern, everything else works fine.

P.S. And thanks for validating :)

I need an exact lenght of five numbers,

Dear: this is my code:

<div class="item form-group">
   <label class="control-label col-md-3 col-sm-3 col-xs-12" for="supp_zipcode"><?=lang('supp_zipcode')?> 
   <span class="required">*</span></label>
    <div class="col-md-6 col-sm-6 col-xs-12">
      <input id="supp_zipcode" class="form-control col-md-7 col-xs-12" data-validate-length="5" name="supp_zipcode" placeholder="<?=lang('supp_zipcode')?>" required="required" type="number">
   </div>
</div>

But it permits more than five numbers. What is wrong?

Alphanumeric validation

Hi

Great piece of coding, I have one small issue:
I'm unable to get the alphanumeric validation to work, this is my html:

First Name

Any help much appreciated

Thanx

Bob

Custom validation in v1.1.0

How to add custom validation for perticular field in v1.1.0 version

jquery.validate.js uses

$.validator.addMethod("checktags", function(value,element,params) { //add custom method
       
    });

also how to alter validation message. You have mentioned that

Example: for a given type ‘date’ field, lets set a custom (general error) message like so:
validator.message['date'] = 'not a real date';

but what if i have type is text. Should i use
validator.message['text'] = 'insert proper input';

Is there any option for this requirement.
Thanks in advance

Patterns not work without required attribute

Hi,

The inputs configured with patterns work perfectly only with required atribute.
If i remove the required attrb the script not return alerts errors.

There're some way to fix this?

thx a lot.

Reset Validation

Hi, I'm using your validator to validate my form inside a modal bootstrap. I use the same form for CRUD. but the thing is when i close the modal, the validator didn't reset the validation. it stuck there and when i open the popup for view / update, the validation is still there.

how to reset the validator?

thanks
Jan

message

How set message of callback in field?
ex: data-validate-message="this field invalid"

special character

how to validate against special characters like single & double quotes.

how to validate multiple checkbox fields?

eg.

                  <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">Checkbox <span class="required">*</span>
                        </label>
                        <div class="col-md-6 col-sm-6 col-xs-12">
                          <label class="checkbox-inline">
                            <input type="checkbox" id="checkbox1" name="test" value="option1" required="required">checkbox1
                          </label>
                          <label class="checkbox-inline">
                            <input type="checkbox" id="checkbox2" name="test" value="option1" required="required">checkbox2
                          </label>
                          <label class="checkbox-inline">
                            <input type="checkbox" id="checkbox3" name="test" value="option1" required="required">checkbox3
                          </label>
                          <label class="checkbox-inline">
                            <input type="checkbox" id="checkbox4" name="test" value="option1" required="required">checkbox4
                          </label>
                        </div>

realized that just validate a single field after read your source code. Besides, click the submit button
repeatedly will show warning message repeatedly.

Validate Length

When I put data-validate-length="", there is no show me some alert label if there is less or more characters

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.