Commit 6d2c6f13 authored by Cosimo Antonio Volpicelli's avatar Cosimo Antonio Volpicelli
Browse files

add validator

parent 8928ec5b
Loading
Loading
Loading
Loading
+22 −0
Original line number Diff line number Diff line
# Auto detect text files and perform LF normalization
* text=auto

# Custom for Visual Studio
*.cs     diff=csharp
*.sln    merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union

# Standard to msysgit
*.doc	 diff=astextplain
*.DOC	 diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot  diff=astextplain
*.DOT  diff=astextplain
*.pdf  diff=astextplain
*.PDF	 diff=astextplain
*.rtf	 diff=astextplain
*.RTF	 diff=astextplain
+165 −0
Original line number Diff line number Diff line
#################
## Eclipse
#################

*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
.vscode

# External tool builders
.externalToolBuilders/

# Locally stored "Eclipse launch configurations"
*.launch

# CDT-specific
.cproject

# PDT-specific
.buildpath


#################
## Visual Studio
#################

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.sln.docstates

# Build results
[Dd]ebug/
[Rr]elease/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.vspscc
.builds
*.dotCover

## TODO: If you have NuGet Package Restore enabled, uncomment this
#packages/

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf

# Visual Studio profiler
*.psess
*.vsp

# ReSharper is a .NET coding add-in
_ReSharper*

# Installshield output folder
[Ee]xpress

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish

# Others
[Bb]in
[Oo]bj
sql
TestResults
*.Cache
ClientBin
stylecop.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects

# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML



############
## Windows
############

# Windows image file caches
Thumbs.db

# Folder config file
Desktop.ini


#############
## Python
#############

*.py[co]

# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg

# Installer logs
pip-log.txt

# Unit test / coverage reports
.coverage
.tox

#Translations
*.mo

#Mr Developer
.mr.developer.cfg

# Mac crap
.DS_Store
/.npmrc
+251 −0
Original line number Diff line number Diff line
<h1 align="center">
  <a href='https://yaireo.github.io/validator'>Validator</a> - Lightweight & Easy HTML form <em>inputs</em> checker
</h1>
<a href='https://www.npmjs.com/package/@yaireo/validator'>
    <img src="https://img.shields.io/npm/v/@yaireo/validator.svg" />
</a>

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

# [👉 See Demo](http://yaireo.github.io/validator)

    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 the JS for – `<input type='foo' name='bar' />`. (Support is synthesized)

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


## Basic semantics
```html
<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 to disable the native HTML5 validations (which currently suck). proceeding it 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 times field groups that are visually separated from each other for example. Now, we treat every form field element the user interacts with, whatsoever, as an “field”, and therefor these “fields” will be wraped with `<div class='field'>`. This isolation gives great powers.
Next, inside an 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 require 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                                                                                                                                                                                                                                                                                                                         |
|---------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <pre>required</pre>                   | Defines that this field should be validated (with JS by my implementation and not via native HTML5 browser defaults)                                                                                                                                                                                                            |
| <pre>placeholder</pre>                | Writes some placeholder text which usually describes the fields with some example input (not supported in IE8 and below)                                                                                                                                                                                                        |
| <pre>pattern</pre>                    | Defines a pattern which the field is evaluated with. Out-of-the-boxvailable values are:<br>**numeric** - Allow only numbers<br>**alphanumeric** - Allow only numbers or letters. No special language characters<br>**phone** - Allow only numbers, spaces or dashes.<br><br>Alternatively, you may write your own custom regex here as well |
| <pre>data-validate-words</pre>        | Defines the minimum amount of words for this field                                                                                                                                                                                                                                                                              |
| <pre>data-validate-length</pre>       | 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                                                                                                                                                            |
| <pre>data-validate-length-range</pre> | 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                                                                                                                                                                             |
| <pre>data-validate-linked</pre>       | Defines the field which the current field’s value (the attribute is set on) should be compared to. Value can be a selector or another input's `name` attribute's value                                                                                                                                                          |
| <pre>data-validate-minmax</pre>       | For type `number` only. Defines the minimum and/or maximum value that can be in that 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:

```html
<input type="text" required="required" pattern="myCustomRegex" />
```

```js
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
This is the object which holds all the texts used by the form validator:

```js
{
    invalid         : 'inupt 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 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-ride.
Example: for a given type ‘date’ field, lets set a custom (general error) message like so:

```js
// 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 (per field) can be disabled:

```js
    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.

```js
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)

```js
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:

```js
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:

```js
// 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 **&lt;div class='tooltip help'&gt;**, which work using pure CSS, are element which holds a small **'?'** icon and when hovered over with the mouse, reveals 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:

```js
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 use as 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 ‘multifield.js’ file.
 No newline at end of file
+123 −0
Original line number Diff line number Diff line
html, body{ height:100%; }
/* body min-width is 992px because it's 960px grid + extra 16px from each side of the header */
body{ min-width:960px; color:#444; background-color:#F1F1F1; font-size:12px; line-height:1.5em; font-family:Arial, Helvetica, sans-serif; }

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    vertical-align:baseline;
}

small{ font-size:0.9em; }

article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display:block;
}

h1{ font-size:2em; margin:0 0 50px 0; }
button{ cursor:pointer; }
p{ padding:5px 0; }

a{ text-decoration:none; }
.btn{ margin:5px; font-size:1.3em; font-weight:bold; border:2px solid rgba(0,0,0,0.2); display:inline-block; box-shadow:0 -30px 30px -15px #00329B inset, 0 1px 0 rgba(255,255,255,0.3) inset; background:#0088CC; background-repeat:repeat-x; color:#FFF; text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25); border-radius:7px; padding:10px 20px; -webkit-transition:0.15s; transition:0.15s; }
.btn:hover{ background:#0068BA; }
.btn:active{ box-shadow:0 0 0 0 rgba(0, 0, 0, 0.3), 0 -30px 30px -15px #00329B inset, 0 0 6px #00243F inset; }
.btn.github{ float:right; }

#wrap{ padding:50px; width:860px; background-color:#FFF; margin:20px auto; border:1px dashed #AAA; position:relative; }
.options{ position:absolute; top:-1px; right:-1px; background-color:#F1F1F1; padding:4px 0; border-left:1px dashed #AAA; border-bottom:1px dashed #AAA; }
	.options label{ cursor:pointer; margin:0 10px; }

input, textarea{ border:1px solid #D1D1D1; }
input, select{ font-size:inherit; margin:0; }
input:focus, textarea:focus{ border-color:#AAA; }

input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance:none; margin:0; }
input[type=checkbox]{ width:auto; border:none; bottom:-1px; cursor:pointer; margin:2px 8px 0 0; position:relative; transform:scale(1.2); }
button{ font-size:1.1em; padding:5px 25px; }

/* Tooltips helpers */
.field .tooltip{ float:left; top:2px; left:7px; position:relative; z-index:2; }
.field .tooltip:hover{ z-index:3; }
   .field .tooltip > span{ display:inline-block; width:15px; height:15px; line-height:15px; font-size:0.9em; font-weight:bold; text-align:center; color:#FFF; cursor:help; background-color:#00AEEF; position:relative; border-radius:10px; }
    .field .tooltip .content{ opacity:0; width:200px; background-color:#333; color:#FFF; font-size:0.9em; position:absolute; top:0; left:20px; padding:8px; border-radius:6px; pointer-events:none; transition:0.2s cubic-bezier(0.1, 0.1, 0.25, 2); -webkit-transition:0.3s cubic-bezier(0.1, 0.2, 0.5, 2.2); -moz-transition:0.3s cubic-bezier(0.1, 0.2, 0.5, 2.2); }
        .field .tooltip p{ padding:0; }
   .field .tooltip.down .content{ left:auto; right:0; top:30px; }
   .field .tooltip:hover .content{ opacity:1; left:36px; }
      .field .tooltip .content b{ height:0; width:0; border-color:#333 #333 transparent transparent; border-style:solid; border-width:9px 7px; position:absolute; left:-14px; top:8px; }
        .field .tooltip.down .content b{ left:auto; right:6px; top:-10px; border-width:5px; border-color:transparent #333 #333 transparent; }

/* alerts (when validation fails) */
.field .alert{ float:left; margin:-2px 0 0 20px; padding:3px 10px; color:#FFF; border-radius:3px 4px 4px 3px; background-color:#CE5454; max-width:170px; white-space:pre; position:relative; left:-15px; opacity:0; z-index:1; transition:0.15s ease-out; }
.field .alert::after{ content:''; display:block; height:0; width:0; border-color:transparent #CE5454 transparent transparent; border-style:solid; border-width:11px 7px; position:absolute; left:-13px; top:1px; }
.field.bad .alert{ left:0; opacity:1; }


@keyframes shake{
    15%{ transform:translateX(-5px); }
    30%{ transform:translateX(5px); }
	45%{ transform:translateX(-3px); }
	60%{ transform:translateX(3px); }
	75%{ transform:translateX(2px); }
	100%{ transform:none; }
}
@-webkit-keyframes shake{
    25%{ -webkit-transform:translateX(-6px); }
    75%{ -webkit-transform:translateX(6px); }
}

form fieldset{ clear:both; margin:0 0 10px 0; }
form .field{ padding:5px 0; position:relative; height:2em; }
form .field.fields{ height:auto; }
	.field label, .field .label{  cursor:pointer; }
		.field label > span:first-child, .field .label{ float:left; width:160px; text-transform:capitalize; line-height:2em; }
	.field input, .field textarea{ float:left; padding:3px 4px; width:210px; -webkit-transition:0.2s; -moz-transition:0.2s; transition:0.2s; }
	.field input[type=checkbox]{ width:auto; }

	.label ~ label{ vertical-align:middle; margin:0.3em 1.2em 0 0; }

	.field input.short{ width:90px; }
	.field input:focus:not([type="checkbox"]), .field textarea:focus{ box-shadow:0 0 4px #00AEEF; border:1px solid #00AEEF; }
	.field textarea{  }
	.field select{ float:left; width:220px; padding:2px 0; margin:0; border:1px solid #CCC; text-transform:capitalize; }
		.field select option{ padding:1px; }

    .field > .extra{ float:left; font-size:0.9em; color:#999; line-height:2em; margin-left:13px; }

	.field.multi .input{ float:left; }
		.field.multi input{ float:left; margin-right:5px; width:35px; text-align:center; }
		form .field.multi input:nth-last-child(-n+2){ margin:0; }
	.field.fields input{ border-top:5px solid #E1E1E1; margin:0 0 0 160px; }

	.bad input,
	.bad select,
	.bad textarea{ border:1px solid #CE5454; box-shadow:0 0 4px -2px #CE5454; position:relative; left:0; -moz-animation:.4s 1 shake ease; -webkit-animation:0.4s 1 shake ease; }


/* mode2 - where the label's text is above the field and not next to it
--------------------------------------------------------------------------- */
.mode2 .field{ float:left; clear:left; margin-bottom:30px; height:auto; padding:0; zoom:1; }
.mode2 .field.bad{ margin-bottom:8px; }
.mode2 .field::before, .mode2 .field::after{ content:''; display:table; }
.mode2 .field::after{ clear:both; }
	.mode2 .field label{  }
		.mode2 .field label span{ float:none; display:block; line-height:inherit; }
	.mode2 .field input:not(type="checkbox"), .field textarea{ width:250px; margin:0; }
	.mode2 .field textarea{ width:350px; margin:0; }
	.mode2 .field select{ width:260px; float:none; }
	.mode2 .field.multi label{ float:none; }
	.mode2 .field.multi input{ float:left; margin-right:5px; width:35px; text-align:center; }
	.mode2 .field .tooltip{ left:auto; position:absolute; right:-22px; top:19px; }
	.mode2 .field .alert::after{ display:none; }
	.mode2 .field .alert{ float:none; clear:left; margin:0; padding:0 5px; border-radius:0 0 3px 3px; max-width:100%; height:22px; line-height:1.8em; }
    .mode2 .field > .extra{ position:absolute; right:0; }
 No newline at end of file
+275 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading