{"id":15379301,"url":"https://github.com/yaireo/validator","last_synced_at":"2025-04-04T21:11:11.417Z","repository":{"id":6103391,"uuid":"7330832","full_name":"yairEO/validator","owner":"yairEO","description":"HTML form validation. Perfectly made for all scenerios, lightweight, semantic \u0026 easy to use","archived":false,"fork":false,"pushed_at":"2021-08-01T19:39:20.000Z","size":160,"stargazers_count":262,"open_issues_count":7,"forks_count":84,"subscribers_count":19,"default_branch":"master","last_synced_at":"2025-03-27T20:47:10.718Z","etag":null,"topics":["form-validation","html"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yairEO.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-12-26T19:07:59.000Z","updated_at":"2025-02-17T14:58:58.000Z","dependencies_parsed_at":"2022-09-13T02:32:10.002Z","dependency_job_id":null,"html_url":"https://github.com/yairEO/validator","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yairEO%2Fvalidator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yairEO%2Fvalidator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yairEO%2Fvalidator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yairEO%2Fvalidator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yairEO","download_url":"https://codeload.github.com/yairEO/validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247249532,"owners_count":20908212,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["form-validation","html"],"created_at":"2024-10-01T14:18:45.584Z","updated_at":"2025-04-04T21:11:11.388Z","avatar_url":"https://github.com/yairEO.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003e\n  \u003ca href='https://yaireo.github.io/validator'\u003eValidator\u003c/a\u003e - Lightweight \u0026 Easy HTML form \u003cem\u003einputs\u003c/em\u003e checker\n\u003c/h1\u003e\n\u003ca href='https://www.npmjs.com/package/@yaireo/validator'\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/@yaireo/validator.svg\" /\u003e\n\u003c/a\u003e\n\nThe Validator is cross-browser and will give you the power to use future-proof input types such as:\u003cbr\u003e\n`tel`, `email`, `number`, `date`, `time`, `checkbox` and `url`.\n\n# [👉 See Demo](http://yaireo.github.io/validator)\n\n    npm i @yaireo/validator --save\n\n    // usage:\n\n    import FormValidator from '@yaireo/validator'\n\n    // or download the `validator.js` file and add load it inside your HTML file\n    \u003cscript src='validator.js'\u003e\u003c/script\u003e\n\n### Why should you use this?\n\n* Cross browser validation\n* Deals with all sorts of edge cases\n* Utilize new HTML5 types for unsupported browsers\n* Flexible error messaging system\n* Light-weight (19kb + comments, unminified)\n\n## Validation types support\nHTML5 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?\n\nFor a full list of all the available types, visit the working draft page.\nThese input types can be validated by the JS for – `\u003cinput type='foo' name='bar' /\u003e`. (Support is synthesized)\n\n✔️ `text` \u003cbr/\u003e\n✔️ `email` \u003cbr/\u003e\n✔️ `password` - also comparing \"re-type password\" inputs\u003cbr/\u003e\n✔️ `number` \u003cbr/\u003e\n✔️ `date` \u003cbr/\u003e\n✔️ `time` \u003cbr/\u003e\n✔️ `uRL` \u003cbr/\u003e\n✔️ `search` \u003cbr/\u003e\n✔️ `file` \u003cbr/\u003e\n✔️ `tel` \u003cbr/\u003e\n✔️ `checkbox` \u003cbr/\u003e\n✔️ `select` \u003cbr/\u003e\n✔️ `textarea`\u003cbr/\u003e\n✔️ `hidden` – can also have the ‘required’ attribute\n\n\n## Basic semantics\n```html\n\u003cform action=\"\" method=\"post\" novalidate\u003e\n    \u003cfieldset\u003e\n        \u003cdiv class=\"field\"\u003e\n            \u003clabel\u003e\n                \u003cspan\u003eName\u003c/span\u003e\n                \u003cinput data-validate-length-range=\"6\" data-validate-words=\"2\" name=\"name\" placeholder=\"ex. John f. Kennedy\" required=\"required\" type=\"text\" /\u003e\n            \u003c/label\u003e\n            \u003cdiv class='tooltip help'\u003e\n                \u003cspan\u003e?\u003c/span\u003e\n                \u003cdiv class='content'\u003e\n                    \u003cb\u003e\u003c/b\u003e\n                    \u003cp\u003eName must be at least 2 words\u003c/p\u003e\n                \u003c/div\u003e\n            \u003c/div\u003e\n        \u003c/div\u003e\n        \u003cdiv class=\"field\"\u003e\n            \u003clabel\u003e\n                \u003cspan\u003eemail\u003c/span\u003e\n                \u003cinput name=\"email\" required=\"required\" type=\"email\" /\u003e\n            \u003c/label\u003e\n        \u003c/div\u003e\n            ...\n```\n\nFirst, 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 `\u003cdiv class='field'\u003e`. This isolation gives great powers.\nNext, inside a field, there will typically be an input or select or something of the sort, so they are put inside a `\u003clabel\u003e` 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 `\u003cspan\u003e` to have control over it’s style.\n\nThe whole approach here is to define each form field (input, select, whatever) as much as possible with HTML5 attributes and also with custom attributes.\n\n\n### HTML Attributes on form elements\n\n| Attribute                    | Purpose                                                                                                                                                                                                                                                                                                                                     |\n| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `required`                   | Defines that this field should be validated (with JS by my implementation and not via native HTML5 browser defaults)                                                                                                                                                                                                                        |\n| `placeholder`                | Writes some placeholder text which usually describes the fields with some example input (not supported in IE8 and below)                                                                                                                                                                                                                    |\n| `pattern`                    | Defines a pattern which the field is evaluated with. Out-of-the-box available values are:\u003cbr\u003e**numeric** - Allow only numbers\u003cbr\u003e**alphanumeric** - Allow only numbers or letters. No special language characters\u003cbr\u003e**phone** - Allow only numbers, spaces or dashes.\u003cbr\u003e\u003cbr\u003eAlternatively, you may write your own custom regex here as well |\n| `data-validate-words`        | Defines the minimum amount of words for this field                                                                                                                                                                                                                                                                                          |\n| `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                                                                                                                                                                        |\n| `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                                                                                                                                                                                         |\n| `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                                                                                                                                                                      |\n| `data-validate-minmax`       | For type `number` only. Defines the minimum and/or maximum value that can be in that field                                                                                                                                                                                                                                                  |\n| `data-validate-text-invalid` | Error text message for specific field\n### `pattern` attribute\nIt is possible to write your own unique Regex patterns directly in the attribute or reference to it by custom name, for example:\n\n```html\n\u003cinput type=\"text\" required=\"required\" pattern=\"myCustomRegex\" /\u003e\n```\n\n```js\nvar validator = new FormValidator({\n    regex : {\n        myCustomRegex: '/whatever/'\n    }\n}, );\n```\n\n### Optional fields\nThere 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.\n\n## Error messages\n\n```js\n{\n    invalid         : 'input is not as expected',\n    short           : 'input is too short',\n    long            : 'input is too long',\n    checked         : 'must be checked',\n    empty           : 'please put something here',\n    select          : 'Please select an option',\n    number_min      : 'too low',\n    number_max      : 'too high',\n    url             : 'invalid URL',\n    number          : 'not a number',\n    email           : 'email address is invalid',\n    email_repeat    : 'emails do not match',\n    date            : 'invalid date',\n    time            : 'invalid time',\n    password_repeat : 'passwords do not match',\n    no_match        : 'no match',\n    complete        : 'input is not complete'\n}\n```\n\nThis 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.\nDefault messages can be over-ridden.\n\n### Example of a specific input field's error message:\n```html\n\u003cinput type=\"text\" data-validate-length-range=\"2,6\" required=\"required\" pattern=\"alphanumeric\"  data-validate-text-invalid='Please follow the pattern rules'/\u003e\n```\n\n### Another example:\n```html\n\u003cinput type=\"text\" name=\"mySpecialInput\" data-validate-length-range=\"2,6\" required=\"required\" pattern=\"alphanumeric\" /\u003e\n```\n\n```js\nvar validator = new FormValidator({\n    texts : {\n        mySpecialInput: 'wrong input' // set custom error message for that specific field, by \"name\"\n    }\n});\n```\n\n### Example: for a given type `date` field, lets set a custom (general error) message like so:\n\n```js\n// set custom text on initialization:\nvar validator = new FormValidator({\n    texts : {\n        date: 'not a real date'\n    }\n});\n\n// or post-initialization\nvar validator = new FormValidator();\nvalidator.texts.date = 'not a real date';\n```\n\nError messages can be disabled:\n\n```js\n    validator = new FormValidator({\n        alerts: false\n    });\n\n    // or by:\n    var validator = new FormValidator();\n    validator.settings.alerts = false;\n```\n\n## Binding the validation to a form\n\nThere 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.\nThe 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).\n\n### Usage example - validate on submit\n\nA generic callback function to have the form validated on the **Submit** event. You can also include your own personal validations before the **checkAll()** call.\n\n```js\nvar validator = new FormValidator();\n// select your \"form\" element from the DOM and attach an \"onsubmit\" event handler to it:\ndocument.forms[0].onsubmit = function(e){\n    var validatorResult = validator.checkAll(this); // \"this\" reffers to the currently submitetd form element\n\n    return !!validatorResult.valid;\n};\n```\n\n### Usage example - validate on field blur/input/change events\nCheck every field (using event Capture)\n\n```js\nvar validator = new FormValidator();\n\ndocument.forms[0].addEventListener('blur', function(e){\n    validator.checkField(e.target)\n}, true);\n\ndocument.forms[0].addEventListener('input', function(e){\n    validator.checkField(e.target);\n}, true);\n\ndocument.forms[0].addEventListener('change', function(e){\n    validator.checkField(e.target)\n}, true);\n```\n\nUtilize 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:\n\n```js\nvar validator = new FormValidator( document.forms[0], {\n    \"events\" : ['blur', 'input', 'change'] // for a single one, just pass a string, ex: \"blur\"\n});\n```\n\nIn 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:\n\n```js\n// validate fields on these events:\n\nvar validator = new FormValidator(document.forms[0]); // the \"\u003cform\u003e\" element should be passed when the instance is created or passed to the \"events\" method below (as the 2nd parameter)\n\n// wait for the form, or its' fields, to be ready (for whatever reason), and then bind the events as follows:\nvalidator.events(['blur', 'input', 'change']);\n```\n\n## Tooltips (for each field which did not validate)\n\nThe helper tooltips **\u0026lt;div class='tooltip help'\u0026gt;**, 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.\n\n## Classes\n`validator.settings.classes` object can be modified:\n\n```js\nvar validatorClasses = {\n    field : 'field', // class for each input wrapper\n    alert : 'alert', // call on the alert tooltip\n    bad   : 'bad'    // classes for bad input\n};\n\nvalidator = new FormValidator(null, {classes:validatorClasses});\n\n// or\nvalidator = new FormValidator();\nvalidator.settings.classes.bad = 'error';\n```\n\n## Bonus – multifields\n\nI have a cool feature I wrote which I call *\"multifields\"*.\nThese 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyaireo%2Fvalidator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyaireo%2Fvalidator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyaireo%2Fvalidator/lists"}