check-rule-mate 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,11 +2,16 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- A lightweight and reusable JavaScript "library" for data validation. This library was esigned to simplify the process of validating form inputs using flexible rules and error handling. Validating your data by allowing you to define flexible rules, custom error messages, and reusable helper functions—all in a structured format.
5
+ A lightweight and reusable JavaScript "library" for data validation. This library was designed to simplify the process of validating form inputs using flexible rules and error handling. Validating your data by allowing you to define flexible rules, custom error messages, and reusable helper functions—all in a structured format.
6
6
 
7
7
  The core goal is to provide a **reusable and easy-to-extend** for handling various form inputs, including fields like name, email, birthdate, phone number, and more.
8
8
 
9
- Test the core functionalities here: [check-rule-mate Demo](https://johnrock16.github.io/check-rule-mate/)
9
+
10
+ **Github repository:** [check-rule-mate repository](https://github.com/johnrock16/check-rule-mate)
11
+
12
+ **Examples of how implement check-rule-mate:** [check-rule-mate examples](#Example-Usage)
13
+
14
+ Test the core functionalities here: [check-rule-mate demo](https://johnrock16.github.io/check-rule-mate/)
10
15
  (Note: Creating or modifying custom validators is not supported in the demo, as it requires JavaScript implementation.)
11
16
 
12
17
 
@@ -23,6 +28,7 @@ Test the core functionalities here: [check-rule-mate Demo](https://johnrock16.gi
23
28
  - **Modifiers:** Extend rules for specific use cases (e.g., age validation in a date rule).
24
29
  - **Dynamic Parameters:** Use $variable to access field data within rules.
25
30
  - **Modular Rules and Validators:** Create multiple files for rules and helpers, organizing them by context or form.
31
+ - **Async Validations:** You could create async functions to validate some data. Do You need to use a fetch or wait a promise to be resolved? No problems.
26
32
 
27
33
  ## Table of Contents
28
34
 
@@ -68,23 +74,29 @@ Here’s an example of validating a set of fields:
68
74
  const CONTACT_US = require('./dataValidator/rules/data/contactUs.json');
69
75
  const MY_VALIDATION_ERROR_MESSAGES = require('./i18n/en_US/errors/myValidatorRules.json');
70
76
 
71
- const fields = {
72
- name: "John",
73
- lastName: "Doe",
74
- email: "email@email.com",
75
- emailConfirm: "email@email.com",
76
- phone: "",
77
- subject: "I need a coffee",
78
- message: "Give me coffee"
79
- };
80
-
81
- // This should return { ok: true }
82
- const result = dataValidate(fields, {
83
- validationHelpers: myValidator,
84
- rules: MY_RULES,
85
- dataRule: CONTACT_US,
86
- dataErrorMessages: MY_VALIDATION_ERROR_MESSAGES,
87
- });
77
+ async function runDataValidate() {
78
+ const fields = {
79
+ name: "John",
80
+ lastName: "Doe",
81
+ email: "email@email.com",
82
+ emailConfirm: "email@email.com",
83
+ phone: "",
84
+ subject: "I need a coffee",
85
+ message: "Give me coffee"
86
+ };
87
+
88
+ // This should return { ok: true }
89
+ const result = await dataValidate(fields, {
90
+ validationHelpers: myValidator,
91
+ rules: MY_RULES,
92
+ dataRule: CONTACT_US,
93
+ dataErrorMessages: MY_VALIDATION_ERROR_MESSAGES,
94
+ });
95
+
96
+ console.log(result);
97
+ }
98
+
99
+ runDataValidate();
88
100
  ```
89
101
 
90
102
  #### Parameters for dataValidate:
@@ -184,7 +196,25 @@ const myValidator = function (value, rule, modifier = null, data = null) {
184
196
  return value === data[key];
185
197
  }
186
198
 
187
- return { regex, hasText, equals };
199
+ async function isDataFetched() {
200
+ try {
201
+ let result = await new Promise((resolve, reject) => {
202
+ setTimeout(() => {
203
+ const success = !!value;
204
+ if (success) {
205
+ resolve('Data fetched successfully!');
206
+ } else {
207
+ reject('Error fetching data');
208
+ }
209
+ }, 2000);
210
+ });
211
+ return !!result;
212
+ } catch (error) {
213
+ return false;
214
+ }
215
+ }
216
+
217
+ return { regex, hasText, equals, isDataFetched };
188
218
  };
189
219
  ```
190
220
 
@@ -198,13 +228,44 @@ Define custom error messages in a structured format:
198
228
  }
199
229
  ```
200
230
 
201
- ### Example Usage
231
+ ## Example Usage
232
+
233
+ Explore examples in the examples folder folder. **Before execute any test change the type in package.json for module instead commonjs**
202
234
 
203
- Explore examples in the examples folder folder.
235
+ **Examples folder**: [Github repo examples folder.](https://github.com/johnrock16/check-rule-mate/tree/main/examples)
204
236
 
205
- #### Vanilla
237
+ ### Vanilla
206
238
  Here you are free to test anything you want about form validation, also We have a lot of tests scenarios in __tests__ which could be a great start.
207
- #### Express:
239
+
240
+ Command to run Vanilla example:
241
+ ```bash
242
+ npm run example:vanilla
243
+ ```
244
+
245
+ **Vanilla example**: [Github repo vanilla file.](https://github.com/johnrock16/check-rule-mate/blob/main/examples/vanilla/src/index.js)
246
+
247
+
248
+ #### __tests__
249
+
250
+ Command to run tests:
251
+ ```bash
252
+ npm run test
253
+ ```
254
+
255
+ **Unit tests examples:** [Github repo unit tests file.](https://github.com/johnrock16/check-rule-mate/blob/main/examples/vanilla/src/__tests__/dataValidator.test.js)
256
+
257
+ ### Express:
208
258
  See how the check-rule-mate works in back-end using a middleware.
209
- #### Frontend:
259
+
260
+ Command to run Express example:
261
+ ```bash
262
+ npm run example:express
263
+ ```
264
+
265
+ **Express example:** [Github repo express file.](https://github.com/johnrock16/check-rule-mate/blob/main/examples/express/src/main.js)
266
+
267
+
268
+ ### Frontend:
210
269
  Here you can found the DEMO page and it's a type of "playground" to test how RULES works and validations works. (Here you can't create customized javascript so custom validatorHelpers are disabled by default)
270
+
271
+ **Frontend example:** [check-rule-mate demo.](https://johnrock16.github.io/check-rule-mate/)
package/dist/main.cjs.js CHANGED
@@ -1 +1 @@
1
- var g=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var E=(n,s)=>{for(var u in s)g(n,u,{get:s[u],enumerable:!0})},v=(n,s,u,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let f of b(s))!q.call(n,f)&&f!==u&&g(n,f,{get:()=>s[f],enumerable:!(a=O(s,f))||a.enumerable});return n};var R=n=>v(g({},"__esModule",{value:!0}),n);var I={};E(I,{dataValidate:()=>m});module.exports=R(I);function m(n,{validationHelpers:s={},rules:u,dataRule:a,dataErrorMessages:f={}}){let p={};function y(r,l){if(!r||typeof l!="string")return;let t=l.split("."),o=r;for(let d of t){if(o[d]===void 0)return;o=o[d]}return o}function i(r,l=null){let{rule:t,required:o}=a[r.key];if((t&&o||!o&&r.value!="")&&t){let d=t.split("--")[0],e=t.split("--").length>1?t.split("--")[1]:"",V=j(r.value,u[d],e,s,l),{isValid:h,errorMessage:k,errorType:M}=V.validate();return h||(p[r.key]={name:r.key,error:!0,errorMessage:y(f,k)||k,errorType:M}),h}return!0}function c(){let r=Object.keys(n).map(l=>({key:l,value:n[l]}));if(r&&r.length>0){if(!Object.keys(a).every(e=>n.hasOwnProperty(e)))return{error:!0,errorMessage:"Missing properties"};if([...r].map(e=>i(e,n)).some(e=>!e))return{error:!0,dataErrors:p};let t=Object.keys(a).map(e=>({key:e,required:a[e].required})),o=r.map(e=>e.key);if(!t.filter(e=>e.required).map(e=>e.key).every(e=>o.includes(e)))return{error:!0}}else if(!r||r.length===0)return{error:!0,errorMessage:"Missing fields for dataRules"};return{ok:!0}}return c()}function j(n,s,u=null,a=null,f=null){function p(i){let c,r;return{isValid:!i.validate.some(t=>{let o=!0;if(i.params&&i.params[t]&&i.params[t].length>0){let d=i.params[t].map(e=>typeof e=="string"&&e[0]==="$"?e.substring(1,e.length):e);o=!this[t](...d)}else o=!this[t]();return o&&!c&&(i!=null&&i.error[t])&&(c=i.error[t],r=t),o}),errorMessage:c,errorType:r}}function y(){if(a&&typeof a=="function"){let i=a(n,s,u,f);Object.keys(i).forEach(c=>{this[c]=i[c]})}return u?p.call(this,s.modifier[u]):p.call(this,s)}return{validate:y}}0&&(module.exports={dataValidate});
1
+ var h=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var O=(n,s)=>{for(var o in s)h(n,o,{get:s[o],enumerable:!0})},b=(n,s,o,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let u of R(s))!M.call(n,u)&&u!==o&&h(n,u,{get:()=>s[u],enumerable:!(i=w(s,u))||i.enumerable});return n};var q=n=>b(h({},"__esModule",{value:!0}),n);var P={};O(P,{dataValidate:()=>V});module.exports=q(P);function V(n,{validationHelpers:s={},rules:o,dataRule:i,dataErrorMessages:u={}}){let y={};function g(e,f){if(!e||typeof f!="string")return;let l=f.split("."),t=e;for(let c of l){if(t[c]===void 0)return;t=t[c]}return t}async function a(e,f=null){let{rule:l,required:t}=i[e.key];if((l&&t||!t&&e.value!="")&&l){let c=l.split("--")[0],r=l.split("--").length>1?l.split("--")[1]:"",m=E(e.value,o[c],r,s,f),{isValid:p,errorMessage:v,errorType:k}=await m.validate();return p||(y[e.key]={name:e.key,error:!0,errorMessage:g(u,v)||v,errorType:k}),p}return!0}async function d(){let e=Object.keys(n).map(f=>({key:f,value:n[f]}));if(e&&e.length>0){if(!Object.keys(i).every(r=>n.hasOwnProperty(r)))return{error:!0,errorMessage:"Missing properties"};if((await Promise.all([...e].map(async r=>await a(r,n)))).some(r=>!r))return{error:!0,dataErrors:y};let l=Object.keys(i).map(r=>({key:r,required:i[r].required})),t=e.map(r=>r.key);if(!l.filter(r=>r.required).map(r=>r.key).every(r=>t.includes(r)))return{error:!0}}else if(!e||e.length===0)return{error:!0,errorMessage:"Missing fields for dataRules"};return{ok:!0}}return d()}function E(n,s,o=null,i=null,u=null){async function y(a){let d,e;return{isValid:!(await Promise.all(a.validate.map(async t=>{let c=!0;if(a.params&&a.params[t]&&a.params[t].length>0){let r=a.params[t].map(p=>typeof p=="string"&&p[0]==="$"?p.substring(1,p.length):p);c=await this[t](...r)}else c=await this[t]();return!c&&!d&&(a!=null&&a.error[t])&&(d=a.error[t],e=t),c}))).some(t=>!t),errorMessage:d,errorType:e}}async function g(){if(i&&typeof i=="function"){let d=i(n,s,o,u);Object.keys(d).forEach(e=>{this[e]=d[e]})}return o?await y.call(this,s.modifier[o]):await y.call(this,s)}return{validate:g}}0&&(module.exports={dataValidate});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "check-rule-mate",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "",
5
5
  "main": "./dist/main.cjs.js",
6
6
  "type": "commonjs",
@@ -21,7 +21,7 @@ export function dataValidate(data, {validationHelpers = {}, rules, dataRule, dat
21
21
  return current;
22
22
  }
23
23
 
24
- function inputValidation(dataAttribute, data = null) {
24
+ async function inputValidation(dataAttribute, data = null) {
25
25
  const { rule, required } = dataRule[dataAttribute.key];
26
26
 
27
27
  if ((rule && required) || (!required && dataAttribute.value != '')) {
@@ -29,7 +29,7 @@ export function dataValidate(data, {validationHelpers = {}, rules, dataRule, dat
29
29
  const INPUT_RULE = rule.split('--')[0];
30
30
  const RULE_MODIFIER = rule.split('--').length > 1 ? rule.split('--')[1] : '';
31
31
  const dataAttributeValidation = dataAttributeValidator(dataAttribute.value, rules[INPUT_RULE], RULE_MODIFIER, validationHelpers, data);
32
- const { isValid, errorMessage, errorType } = dataAttributeValidation.validate();
32
+ const { isValid, errorMessage, errorType } = await dataAttributeValidation.validate();
33
33
  if (!isValid) {
34
34
  dataErrors[dataAttribute.key] = {
35
35
  name: dataAttribute.key,
@@ -44,13 +44,13 @@ export function dataValidate(data, {validationHelpers = {}, rules, dataRule, dat
44
44
  return true;
45
45
  }
46
46
 
47
- function validate() {
47
+ async function validate() {
48
48
  let dataArr = Object.keys(data).map((key) => ({ key, value: data[key] }));
49
49
  if (dataArr && dataArr.length > 0) {
50
50
  if(!Object.keys(dataRule).every((key) => data.hasOwnProperty(key))) {
51
51
  return { error: true, errorMessage: "Missing properties"}
52
52
  }
53
- const dataValidators = [...dataArr].map((input) => inputValidation(input, data));
53
+ const dataValidators = await Promise.all([...dataArr].map(async (input) => await inputValidation(input, data)));
54
54
 
55
55
  if (dataValidators.some((element) => !element)) {
56
56
  return { error: true, dataErrors: dataErrors };
@@ -82,35 +82,38 @@ export function dataValidate(data, {validationHelpers = {}, rules, dataRule, dat
82
82
  * @returns {{validate: Function}} the built function to validate all this parameters
83
83
  */
84
84
  function dataAttributeValidator (value, rule, modifier = null, customValidation = null, data = null) {
85
- function validateRules(rule) {
85
+ async function validateRules(rule) {
86
86
  let errorMessage;
87
87
  let errorType;
88
- const isValid = !rule.validate.some((validation) => {
89
- let isInvalid = true;
88
+ const validations = await Promise.all(rule.validate.map(async (validation) => {
89
+ let isValid = true;
90
90
  if ((rule.params && rule.params[validation] && rule.params[validation].length > 0)) {
91
91
  const params = rule.params[validation].map((param) => (typeof param === 'string' && param[0] === '$') ? param.substring(1, param.length) : param);
92
- isInvalid = !this[validation](...params)
92
+ const validateResponse = await this[validation](...params);
93
+ isValid = validateResponse;
93
94
  } else {
94
- isInvalid = !this[validation]()
95
+ const validateResponse = await this[validation]();
96
+ isValid = validateResponse;
95
97
  }
96
- if (isInvalid && !errorMessage && rule?.error[validation]) {
98
+ if (!isValid && !errorMessage && rule?.error[validation]) {
97
99
  errorMessage = rule.error[validation];
98
100
  errorType = validation;
99
101
  }
100
- return isInvalid;
101
- });
102
+ return isValid;
103
+ }));
104
+ const isValid = !validations.some((validation) => !validation);
102
105
  return {isValid, errorMessage, errorType}
103
106
  }
104
107
 
105
- function validate() {
108
+ async function validate() {
106
109
  if (customValidation && typeof customValidation === 'function') {
107
110
  const validation = customValidation(value, rule, modifier, data);
108
111
  Object.keys(validation).forEach((key) => {
109
112
  this[key] = validation[key];
110
113
  })
111
114
  }
112
-
113
- return modifier ? validateRules.call(this, rule.modifier[modifier]) : validateRules.call(this, rule);
115
+ const response = modifier ? await validateRules.call(this, rule.modifier[modifier]) : await validateRules.call(this, rule);
116
+ return response;
114
117
  }
115
118
 
116
119
  return({