New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

pristinejs

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pristinejs - npm Package Compare versions

Comparing version

to
0.1.6

39

dist/pristine.js

@@ -37,2 +37,11 @@ (function (global, factory) {

function mergeConfig(obj1, obj2) {
for (var attr in obj2) {
if (!(attr in obj1)) {
obj1[attr] = obj2[attr];
}
}
return obj1;
}
var defaultConfig = {

@@ -102,3 +111,3 @@ classTo: 'form-group',

self.form = form;
self.config = config || defaultConfig;
self.config = mergeConfig(config || {}, defaultConfig);
self.live = !(live === false);

@@ -232,4 +241,3 @@ self.fields = Array.from(form.querySelectorAll(SELECTOR)).map(function (input) {

*
* @param elemOrName => The dom element when validator is applied on a specific field. A string when it's
* a global validator
* @param elem => The dom element where the validator is applied to
* @param fn => validator function

@@ -241,10 +249,10 @@ * @param msg => message to show when validation fails. Supports templating. ${0} for the input's value, ${1} and

*/
self.addValidator = function (elemOrName, fn, msg, priority, halt) {
if (typeof elemOrName === 'string') {
_(elemOrName, { fn: fn, msg: msg, priority: priority, halt: halt });
} else if (elemOrName instanceof HTMLElement) {
elemOrName.pristine.validators.push({ fn: fn, msg: msg, priority: priority, halt: halt });
elemOrName.pristine.validators.sort(function (a, b) {
self.addValidator = function (elem, fn, msg, priority, halt) {
if (elem instanceof HTMLElement) {
elem.pristine.validators.push({ fn: fn, msg: msg, priority: priority, halt: halt });
elem.pristine.validators.sort(function (a, b) {
return b.priority - a.priority;
});
} else {
console.warn("The parameter elem must be a dom element");
}

@@ -365,4 +373,17 @@ };

/***
*
* @param name => Name of the global validator
* @param fn => validator function
* @param msg => message to show when validation fails. Supports templating. ${0} for the input's value, ${1} and
* so on are for the attribute values
* @param priority => priority of the validator function, higher valued function gets called first.
* @param halt => whether validation should stop for this field after current validation function
*/
Pristine.addValidator = function (name, fn, msg, priority, halt) {
_(name, { fn: fn, msg: msg, priority: priority, halt: halt });
};
return Pristine;
})));

@@ -1,1 +0,1 @@

!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):e.Pristine=r()}(this,function(){"use strict";function e(e){var r=arguments;return this.replace(/\${([^{}]*)}/g,function(e,t){return r[t]})}function r(e){return e.pristine.self.form.querySelectorAll('input[name="'+e.getAttribute("name")+'"]:checked').length}function t(r,t,n){function f(e,r,t,n){var i=l[t];if(i&&(e.push(i),n)){var s=n.split(",");s.unshift(null),r[t]=s}}function c(e){if(e.errorElements)return e.errorElements;var r=function(e,r){for(;(e=e.parentElement)&&!e.classList.contains(r););return e}(e.input,d.config.classTo),t=null,n=null;return(t=d.config.classTo===d.config.errorTextParent?r:r.querySelector(d.errorTextParent))&&((n=t.querySelector("."+s))||((n=document.createElement(d.config.errorTextTag)).className=s+" "+d.config.errorTextClass,t.appendChild(n),n.pristineDisplay=n.style.display)),e.errorElements=[r,n]}function p(e){var r=c(e),t=r[0],n=r[1];t&&(t.classList.remove(d.config.successClass),t.classList.add(d.config.errorClass)),n&&(n.innerHTML=e.errors.join("<br/>"),n.style.display=n.pristineDisplay||"")}function m(e){var r=function(e){var r=c(e),t=r[0],n=r[1];return t&&(t.classList.remove(d.config.errorClass),t.classList.remove(d.config.successClass)),n&&(n.innerHTML="",n.style.display="none"),r}(e)[0];r&&r.classList.add(d.config.successClass)}var d=this;return function(e,r,t){e.setAttribute("novalidate","true"),d.form=e,d.config=r||i,d.live=!(!1===t),d.fields=Array.from(e.querySelectorAll(a)).map(function(e){var r=[],t={},n={};return[].forEach.call(e.attributes,function(e){if(/^data-pristine-/.test(e.name)){var i=e.name.substr(14);if(i.endsWith("-message"))return void(n[i.slice(0,i.length-8)]=e.value);"type"===i&&(i=e.value),f(r,t,i,e.value)}else~o.indexOf(e.name)?f(r,t,e.name,e.value):"type"===e.name&&f(r,t,e.value)}),r.sort(function(e,r){return r.priority-e.priority}),d.live&&e.addEventListener(~["radio","checkbox"].indexOf(e.getAttribute("type"))?"change":"input",function(e){d.validate(e.target)}.bind(d)),e.pristine={input:e,validators:r,params:t,messages:n,self:d}}.bind(d))}(r,t,n),d.validate=function(r,t){t=r&&!0===t||!0===r;var n=d.fields;!0!==r&&!1!==r&&(r instanceof HTMLElement?n=[r.pristine]:(r instanceof NodeList||r instanceof(window.$||Array)||r instanceof Array)&&(n=Array.from(r).map(function(e){return e.pristine})));var i=!0;for(var s in n){var a=n[s];!function(r){var t=[],n=!0;for(var i in r.validators){var s=r.validators[i],a=r.params[s.name]?r.params[s.name]:[];if(a[0]=r.input.value,!s.fn.apply(r.input,a)){n=!1;var o=r.messages[s.name]||s.msg;if(t.push(e.apply(o,a)),!0===s.halt)break}}return r.errors=t,n}(a)?(i=!1,!t&&p(a)):!t&&m(a)}return i},d.getErrors=function(e){if(!e){for(var r=[],t=0;t<d.fields.length;t++){var n=d.fields[t];n.errors.length&&r.push({input:n.input,errors:n.errors})}return r}return e.length?e[0].pristine.errors:e.pristine.errors},d.addValidator=function(e,r,t,n,i){"string"==typeof e?u(e,{fn:r,msg:t,priority:n,halt:i}):e instanceof HTMLElement&&(e.pristine.validators.push({fn:r,msg:t,priority:n,halt:i}),e.pristine.validators.sort(function(e,r){return r.priority-e.priority}))},d.addError=function(e,r){(e=e.length?e[0]:e).pristine.errors.push(r),p(e.pristine)},d.reset=function(){for(var e in d.fields)d.fields[e].errorElements=null;Array.from(d.form.querySelectorAll("."+s)).map(function(e){e.parentNode.removeChild(e)}),Array.from(d.form.querySelectorAll("."+d.config.classTo)).map(function(e){e.classList.remove(d.config.successClass),e.classList.remove(d.config.errorClass)})},d.destroy=function(){d.reset(),d.fields.forEach(function(e){delete e.input.pristine}),d.fields=[]},d.setGlobalConfig=function(e){i=e},d}var n={required:"This field is required",email:"This field requires a valid e-mail address",number:"This field requires a number",url:"This field requires a valid website URL",tel:"This field requires a valid telephone number",maxlength:"This fields length must be < ${1}",minlength:"This fields length must be > ${1}",min:"Minimum value for this field is ${1}",max:"Maximum value for this field is ${1}",pattern:"Input must match the pattern ${1}"},i={classTo:"form-group",errorClass:"has-danger",successClass:"has-success",errorTextParent:"form-group",errorTextTag:"div",errorTextClass:"text-help"},s="pristine-error",a="input:not([type^=hidden]):not([type^=submit]), select, textarea",o=["required","min","max","minlength","maxlength","pattern"],l={},u=function(e,r){r.name=e,r.msg||(r.msg=n[e]),void 0===r.priority&&(r.priority=1),l[e]=r};return u("text",{fn:function(e){return!0},priority:0}),u("required",{fn:function(e){return"radio"===this.type||"checkbox"===this.type?r(this):void 0!==e&&""!==e},priority:99,halt:!0}),u("email",{fn:function(e){return!e||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}}),u("number",{fn:function(e){return!e||!isNaN(parseFloat(e))},priority:2}),u("integer",{fn:function(e){return e&&/^\d+$/.test(e)}}),u("minlength",{fn:function(e,r){return!e||e.length>=parseInt(r)}}),u("maxlength",{fn:function(e,r){return!e||e.length<=parseInt(r)}}),u("min",{fn:function(e,t){return!e||("checkbox"===this.type?r(this)>=parseInt(t):parseFloat(e)>=parseFloat(t))}}),u("max",{fn:function(e,t){return!e||("checkbox"===this.type?r(this)<=parseInt(t):parseFloat(e)<=parseFloat(t))}}),u("pattern",{fn:function(e,r){var t=r.match(new RegExp("^/(.*?)/([gimy]*)$"));return!e||new RegExp(t[1],t[2]).test(e)}}),t});
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):e.Pristine=r()}(this,function(){"use strict";function e(e){var r=arguments;return this.replace(/\${([^{}]*)}/g,function(e,t){return r[t]})}function r(e){return e.pristine.self.form.querySelectorAll('input[name="'+e.getAttribute("name")+'"]:checked').length}function t(r,t,n){function u(e,r,t,n){var i=l[t];if(i&&(e.push(i),n)){var s=n.split(",");s.unshift(null),r[t]=s}}function f(e){if(e.errorElements)return e.errorElements;var r=function(e,r){for(;(e=e.parentElement)&&!e.classList.contains(r););return e}(e.input,m.config.classTo),t=null,n=null;return(t=m.config.classTo===m.config.errorTextParent?r:r.querySelector(m.errorTextParent))&&((n=t.querySelector("."+s))||((n=document.createElement(m.config.errorTextTag)).className=s+" "+m.config.errorTextClass,t.appendChild(n),n.pristineDisplay=n.style.display)),e.errorElements=[r,n]}function c(e){var r=f(e),t=r[0],n=r[1];t&&(t.classList.remove(m.config.successClass),t.classList.add(m.config.errorClass)),n&&(n.innerHTML=e.errors.join("<br/>"),n.style.display=n.pristineDisplay||"")}function p(e){var r=function(e){var r=f(e),t=r[0],n=r[1];return t&&(t.classList.remove(m.config.errorClass),t.classList.remove(m.config.successClass)),n&&(n.innerHTML="",n.style.display="none"),r}(e)[0];r&&r.classList.add(m.config.successClass)}var m=this;return function(e,r,t){e.setAttribute("novalidate","true"),m.form=e,m.config=function(e,r){for(var t in r)t in e||(e[t]=r[t]);return e}(r||{},i),m.live=!(!1===t),m.fields=Array.from(e.querySelectorAll(a)).map(function(e){var r=[],t={},n={};return[].forEach.call(e.attributes,function(e){if(/^data-pristine-/.test(e.name)){var i=e.name.substr(14);if(i.endsWith("-message"))return void(n[i.slice(0,i.length-8)]=e.value);"type"===i&&(i=e.value),u(r,t,i,e.value)}else~o.indexOf(e.name)?u(r,t,e.name,e.value):"type"===e.name&&u(r,t,e.value)}),r.sort(function(e,r){return r.priority-e.priority}),m.live&&e.addEventListener(~["radio","checkbox"].indexOf(e.getAttribute("type"))?"change":"input",function(e){m.validate(e.target)}.bind(m)),e.pristine={input:e,validators:r,params:t,messages:n,self:m}}.bind(m))}(r,t,n),m.validate=function(r,t){t=r&&!0===t||!0===r;var n=m.fields;!0!==r&&!1!==r&&(r instanceof HTMLElement?n=[r.pristine]:(r instanceof NodeList||r instanceof(window.$||Array)||r instanceof Array)&&(n=Array.from(r).map(function(e){return e.pristine})));var i=!0;for(var s in n){var a=n[s];!function(r){var t=[],n=!0;for(var i in r.validators){var s=r.validators[i],a=r.params[s.name]?r.params[s.name]:[];if(a[0]=r.input.value,!s.fn.apply(r.input,a)){n=!1;var o=r.messages[s.name]||s.msg;if(t.push(e.apply(o,a)),!0===s.halt)break}}return r.errors=t,n}(a)?(i=!1,!t&&c(a)):!t&&p(a)}return i},m.getErrors=function(e){if(!e){for(var r=[],t=0;t<m.fields.length;t++){var n=m.fields[t];n.errors.length&&r.push({input:n.input,errors:n.errors})}return r}return e.length?e[0].pristine.errors:e.pristine.errors},m.addValidator=function(e,r,t,n,i){e instanceof HTMLElement?(e.pristine.validators.push({fn:r,msg:t,priority:n,halt:i}),e.pristine.validators.sort(function(e,r){return r.priority-e.priority})):console.warn("The parameter elem must be a dom element")},m.addError=function(e,r){(e=e.length?e[0]:e).pristine.errors.push(r),c(e.pristine)},m.reset=function(){for(var e in m.fields)m.fields[e].errorElements=null;Array.from(m.form.querySelectorAll("."+s)).map(function(e){e.parentNode.removeChild(e)}),Array.from(m.form.querySelectorAll("."+m.config.classTo)).map(function(e){e.classList.remove(m.config.successClass),e.classList.remove(m.config.errorClass)})},m.destroy=function(){m.reset(),m.fields.forEach(function(e){delete e.input.pristine}),m.fields=[]},m.setGlobalConfig=function(e){i=e},m}var n={required:"This field is required",email:"This field requires a valid e-mail address",number:"This field requires a number",url:"This field requires a valid website URL",tel:"This field requires a valid telephone number",maxlength:"This fields length must be < ${1}",minlength:"This fields length must be > ${1}",min:"Minimum value for this field is ${1}",max:"Maximum value for this field is ${1}",pattern:"Input must match the pattern ${1}"},i={classTo:"form-group",errorClass:"has-danger",successClass:"has-success",errorTextParent:"form-group",errorTextTag:"div",errorTextClass:"text-help"},s="pristine-error",a="input:not([type^=hidden]):not([type^=submit]), select, textarea",o=["required","min","max","minlength","maxlength","pattern"],l={},u=function(e,r){r.name=e,r.msg||(r.msg=n[e]),void 0===r.priority&&(r.priority=1),l[e]=r};return u("text",{fn:function(e){return!0},priority:0}),u("required",{fn:function(e){return"radio"===this.type||"checkbox"===this.type?r(this):void 0!==e&&""!==e},priority:99,halt:!0}),u("email",{fn:function(e){return!e||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}}),u("number",{fn:function(e){return!e||!isNaN(parseFloat(e))},priority:2}),u("integer",{fn:function(e){return e&&/^\d+$/.test(e)}}),u("minlength",{fn:function(e,r){return!e||e.length>=parseInt(r)}}),u("maxlength",{fn:function(e,r){return!e||e.length<=parseInt(r)}}),u("min",{fn:function(e,t){return!e||("checkbox"===this.type?r(this)>=parseInt(t):parseFloat(e)>=parseFloat(t))}}),u("max",{fn:function(e,t){return!e||("checkbox"===this.type?r(this)<=parseInt(t):parseFloat(e)<=parseFloat(t))}}),u("pattern",{fn:function(e,r){var t=r.match(new RegExp("^/(.*?)/([gimy]*)$"));return!e||new RegExp(t[1],t[2]).test(e)}}),t.addValidator=function(e,r,t,n,i){u(e,{fn:r,msg:t,priority:n,halt:i})},t});
{
"name": "pristinejs",
"version": "0.1.5",
"version": "0.1.6",
"description": "A tiny vanilla javascript form validation library",

@@ -5,0 +5,0 @@ "main": "dist/pristine.js",

@@ -6,3 +6,3 @@ # Pristine - Vanilla javascript form validation library

## [Demo](http://pristine.js.org/demo/)
## [Demo](http://pristine.js.org/demo.html)

@@ -82,3 +82,3 @@ **This documentation is being updated and currently incomplete**

```javascript
Pristine.addValidator(nameOrElem, handler, errorMessage, priority, halt);
pristine.addValidator(nameOrElem, handler, errorMessage, priority, halt);
```

@@ -94,3 +94,4 @@

// A validator to check if the first letter is capitalized
pristine.addValidator(elem, function(value, elem) {
pristine.addValidator(elem, function(value) {
// here `this` refers to the respective input element
if (value.length && value[0] === value[0].toUpperCase()){

@@ -103,9 +104,11 @@ return true;

### Add a global validator
### Add a global custom validator
```javascript
// A validator to check if the input value is within a specified range
Pristine.addValidator("my-range", function(value, elem, val1, val2) {
// Global validators must be added before creating the pristine instance
Pristine.addValidator("my-range", function(value, param1, param2) {
// here `this` refers to the respective input element
return parseInt(param1) <= value && value <= parseInt(param2)
return parseInt(val1) <= value && value <= parseInt(val2)
}, "The value (${0}) must be between ${1} and ${2}", 5, false);

@@ -119,2 +122,9 @@ ```

```
### Add custom error messages
```html
<input required data-pristine-required-message="My custom message"/>
```
Add an attribute like `data-pristine-<ValidatorName>-message`with the custom message as value to show custom error messages. You can add custom messages like this for as many validators as you need. Here `ValidatorName` means `required`, `email`, `min`, `max` etc.
## Built-in validators

@@ -149,3 +159,3 @@

**Pristine.validate(inputs, silent)**
**pristine.validate(inputs, silent)**
<br/>*Validate the form or field(s)*

@@ -161,3 +171,3 @@

**Pristine.addValidator(elemOrName, fn, msg, priority, halt)**
**pristine.addValidator(elem, fn, msg, priority, halt)**
<br/>*Add a custom validator*

@@ -167,3 +177,3 @@

| --- | ---- | ----- | --- |
| `elemOrName`| - | <center>✔</center> | The dom element when validator is applied on a specific field. A string (the name of the validator) when it's a global validator, you can then use `data-pristine-<NAME>` attribute in form fields to apply this validator|
| `elem`| - | <center>✔</center> | The dom element where validator is applied to.|
| `fn`| - | <center>✔</center> | The function that validates the field. Value of the input field gets passed as the first parameter, and the attribute value (split using comma) as the subsequent parameters. For example, for `<input data-pristine-my-validator="10,20,dhaka" value="myValue"/>`, validator function get called like `fn("myValue", 10, 20, "dhaka")`. Inside the function `this` refers to the input element|

@@ -176,3 +186,13 @@ | `message`| - | <center>✔</center> | The message to show when the validation fails. It supports simple templating. `${0}` for the input's value, `${1}` and so on are for the attribute values. For the above example, `${0}` will get replaced by `myValue`, `${1}` by `10`, `${2}` by `20`, `${3}` by `dhaka`.|

**Pristine.getErrors(input)**
**Pristine.addValidator(name, fn, msg, priority, halt)**
<br/>*Add a global custom validator*
| Parameter | Default | Required? | Description|
| --- | ---- | ----- | --- |
| `name`| <center>-</center> | <center>✔</center> | A string, the name of the validator, you can then use `data-pristine-<NAME>` attribute in form fields to apply this validator|
| `....`| - | - | Other parameters same as above |
<br/>
**pristine.getErrors(input)**
<br/>*Get the errors of the form or a specific field*

@@ -187,3 +207,3 @@

**Pristine.addError(input, error)**
**pristine.addError(input, error)**
<br/>*Add A custom error to an input element*

@@ -198,3 +218,3 @@

**Pristine.setGlobalConfig(config)**
**pristine.setGlobalConfig(config)**
<br/>*Set the global configuration*

@@ -208,3 +228,3 @@

**Pristine.reset()**
**pristine.reset()**
<br/>*Reset the errors in the form*

@@ -215,3 +235,3 @@

**Pristine.destroy()**
**pristine.destroy()**
<br/>*Destroy the pristine object*

@@ -218,0 +238,0 @@

import { lang } from './lang';
import { tmpl, findAncestor, groupedElemCount } from './utils';
import { tmpl, findAncestor, groupedElemCount, mergeConfig } from './utils';

@@ -41,7 +41,7 @@ let defaultConfig = {

export default function Pristine(form, config, live){
let self = this;
init(form, config, live);
function init(form, config, live){

@@ -52,3 +52,3 @@

self.form = form;
self.config = config || defaultConfig;
self.config = mergeConfig(config || {}, defaultConfig);
self.live = !(live === false);

@@ -138,5 +138,5 @@ self.fields = Array.from(form.querySelectorAll(SELECTOR)).map(function (input) {

if (!input){
var erroneousFields = [];
for(var i=0; i<self.fields.length; i++){
var field = self.fields[i];
let erroneousFields = [];
for(let i=0; i<self.fields.length; i++){
let field = self.fields[i];
if (field.errors.length){

@@ -180,4 +180,3 @@ erroneousFields.push({input: field.input, errors: field.errors});

*
* @param elemOrName => The dom element when validator is applied on a specific field. A string when it's
* a global validator
* @param elem => The dom element where the validator is applied to
* @param fn => validator function

@@ -189,8 +188,8 @@ * @param msg => message to show when validation fails. Supports templating. ${0} for the input's value, ${1} and

*/
self.addValidator = function(elemOrName, fn, msg, priority, halt){
if (typeof elemOrName === 'string'){
_(elemOrName, {fn, msg, priority, halt});
} else if (elemOrName instanceof HTMLElement){
elemOrName.pristine.validators.push({fn, msg, priority, halt});
elemOrName.pristine.validators.sort( (a, b) => b.priority - a.priority);
self.addValidator = function(elem, fn, msg, priority, halt){
if (elem instanceof HTMLElement){
elem.pristine.validators.push({fn, msg, priority, halt});
elem.pristine.validators.sort( (a, b) => b.priority - a.priority);
} else {
console.warn("The parameter elem must be a dom element");
}

@@ -278,3 +277,3 @@ };

self.reset = function () {
for(var i in self.fields){
for(let i in self.fields){
self.fields[i].errorElements = null;

@@ -309,2 +308,15 @@ }

}
}
/***
*
* @param name => Name of the global validator
* @param fn => validator function
* @param msg => message to show when validation fails. Supports templating. ${0} for the input's value, ${1} and
* so on are for the attribute values
* @param priority => priority of the validator function, higher valued function gets called first.
* @param halt => whether validation should stop for this field after current validation function
*/
Pristine.addValidator = function(name, fn, msg, priority, halt){
_(name, {fn, msg, priority, halt});
};

@@ -12,2 +12,11 @@ export function findAncestor (el, cls) {

return input.pristine.self.form.querySelectorAll('input[name="' + input.getAttribute('name') + '"]:checked').length;
}
}
export function mergeConfig(obj1, obj2) {
for (let attr in obj2) {
if (!(attr in obj1)) {
obj1[attr] = obj2[attr];
}
}
return obj1;
}