Skip to content
This repository was archived by the owner on Feb 7, 2023. It is now read-only.

Commit 43c387f

Browse files
committed
minor corrections; readme content added;
1 parent c2e2e61 commit 43c387f

File tree

3 files changed

+141
-30
lines changed

3 files changed

+141
-30
lines changed

README.md

Lines changed: 128 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1+
### ***Readme and examples are under construction. Please check later***
2+
3+
----
4+
15
# JS Data Validator
26
A JS module for simplifying complexly-structured-data validation.
37

48
----
5-
To load the module in HTML
6-
```html
7-
<script type="module" src="https://cdn.jsdelivr.net/gh/anshu-krishna/JS-Data-Validator@latest/data-validator.min.js"></script>
8-
```
9+
## Installation:
910

10-
To load in JavaScript
1111
```javascript
1212
import {DataValidator} from 'https://cdn.jsdelivr.net/gh/anshu-krishna/JS-Data-Validator@latest/data-validator.min.js';
1313

@@ -16,7 +16,127 @@ import {DataValidator} from 'https://cdn.jsdelivr.net/gh/anshu-krishna/JS-Data-V
1616
const {DataValidator} = await import('https://cdn.jsdelivr.net/gh/anshu-krishna/JS-Data-Validator@latest/data-validator.min.js');
1717
```
1818

19-
---
19+
----
20+
21+
## Features:
22+
* Supported types:
23+
* `bool` : Boolean value
24+
* `email` : String containing an email address
25+
* `float` : Float value
26+
* `hex` : String containing a hex value
27+
* `int` : Int value
28+
* `any` : Any value
29+
* `null` : Null value
30+
* `number` : Int or Float value
31+
* `string` : String value
32+
* `timestamp` : String containing a timestamp.\
33+
eg: '2021-01-31', '01-Jan-2021', 'January 1, 2021 05:00:10 AM GMT+05:30', etc.
34+
* `unsigned` : Int >= 0
35+
* `url` : String containing a URL
36+
37+
* Custom data types can also be added. For example see `example files`
38+
39+
* Multiple alternative data types can be set for a data item. eg: `'int|float|null'`, `'email|null'`, etc.
40+
41+
* Supported Ranger/Formatter
42+
* `num_range` : Works with any numeric data. Sets range (min, max) of the value
43+
* `str_range` : Works with any string data. Sets range (min, max) of the string length
44+
* `str_lower` : Works with any string data. Transforms the string to lowercase
45+
* `str_upper` : Works with any string data. Transforms the string to uppercase
46+
* `str_title` : Works with any string data. Transforms the string to titlecase
47+
* `to_str` : Works with any data. Transfroms the data to a string.
48+
49+
* Custom ranger/formatter can also be added. For example see `example files`
50+
51+
* Data-structure can be of nested style (Upto max recursion depth). For example see `example files`
52+
53+
----
54+
55+
## Basic Example:
56+
```html
57+
<script type="module">
58+
// Load the DataValidator module;
59+
import {DataValidator as DV} from 'https://cdn.jsdelivr.net/gh/anshu-krishna/JS-Data-Validator@latest/data-validator.min.js';
60+
61+
// This is expected structure
62+
const structure = {
63+
name: "string", // Name is a string
64+
id: "int|email", // ID can be an int or email address
65+
age: "int@num_range(18,45)", // Age is an int. Age must be in range [18,45]
66+
"?nums": ["int|float"], // Nums is optional. Nums is an array contaning int and float items
67+
68+
// Links is optional. Links is an array of 'item' arrays. 'item' has Title and Link property
69+
"?links": [{
70+
"title": "string", // Title is a string
71+
"link": "url", // Link is a URL
72+
}]
73+
};
74+
75+
// Create a validator object for the given data-structure
76+
let dv = new DV(structure);
77+
if(dv.hasErrors) { // Check for errors in the structure definition
78+
console.error('Structure has errors:\n', dv.errorString);
79+
} else {
80+
// The validator is ready for use
81+
let validated = dv.validate({
82+
name: "Test User1",
83+
id: "12345",
84+
age: '0b11001',
85+
nums: [1, 2, 3, 4.5, 6.7, 8],
86+
links: [{
87+
title: "Link 1",
88+
link: "http://site1.com/user/12345"
89+
}, {
90+
title: "Link 2",
91+
link: "http://site2.com/user/12345"
92+
}]
93+
});
94+
if(dv.hasErrors) { // Check if data validation was successful
95+
console.error('Data doesnot match the structure:\n', dv.errorString);
96+
} else {
97+
console.log('Data matches the structure:\n', validated);
98+
}
99+
100+
// Next validation
101+
validated = dv.validate({
102+
name: "Test User2",
103+
104+
age: "30", // Integer value in a string
105+
// Optional nums not present
106+
links: [{
107+
title: "Link 1",
108+
link: "http://site1.com/user/56789"
109+
}]
110+
});
111+
112+
if(dv.hasErrors) { // Check if data validation was successful
113+
console.error('Data doesnot match the structure:\n', dv.errorString);
114+
} else {
115+
console.log('Data matches the structure:\n', validated);
116+
}
117+
118+
// Lets do some more validations
119+
validated = dv.validate({id: 78912, age: 70}); // Some missing data. Age is out of range.
120+
121+
if(dv.hasErrors) { // Check if data validation was successful
122+
console.error('Data doesnot match the structure:\n', dv.errorString);
123+
} else {
124+
console.log('Data matches the structure:\n', validated);
125+
}
126+
127+
// Last example
128+
validated = dv.validate({
129+
name: true, // Bool insteadof a string
130+
age: 80,
131+
nums: [1, false, 20, 'hello']
132+
// Optional links not present
133+
});
20134
21-
*Under construction*\
22-
Check later
135+
if(dv.hasErrors) { // Check if data validation was successful
136+
console.error('Data doesnot match the structure:\n', dv.errorString);
137+
} else {
138+
console.log('Data matches the structure:\n', validated);
139+
}
140+
}
141+
</script>
142+
```

data-validator.js

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -387,10 +387,18 @@ class ErrorManager {
387387
}
388388
}
389389
}
390+
static makePrefix(prefix) {
391+
prefix = prefix ?? [];
392+
if(!Array.isArray(prefix)) {
393+
prefix = [prefix];
394+
}
395+
if(prefix.length === 0) {
396+
return '';
397+
}
398+
return `${prefix.map(p=>`[${p}]`).join('')}: `;
399+
}
390400
get errorString() {
391-
return this.errors?.map(e => (e.prefix.length === 0) ? `${e.msg}` : `${e.prefix.map(p => `[${p}]`).join('')}: ${e.msg}`).join('\n') ?? 'null';
392-
// return this.errors?.join('\n') ?? 'null';
393-
// return JSON.stringify(this.errors, null, 4);
401+
return this.errors?.map(e => `${ErrorManager.makePrefix(e.prefix)}${e.msg}`).join('\n') ?? 'null';
394402
}
395403
__inheritErrors__(source, prefix = null) {
396404
const errors = source.errors;
@@ -410,23 +418,6 @@ class ErrorManager {
410418
source.errors = null;
411419
}
412420
}
413-
// class Returner {
414-
// valid = false;
415-
// value = undefined; // Actual value or error message
416-
// constructor(valid, value) {
417-
// this.valid = valid;
418-
// this.value = value;
419-
// }
420-
// static setValid(value) {
421-
// return new Returner(true, value);
422-
// }
423-
// static setInvalid(errorMsg = '') {
424-
// return new Returner(false, errorMsg);
425-
// }
426-
// get error() {
427-
// return this.valid ? this.value : null;
428-
// }
429-
// }
430421
class DataValidator extends ErrorManager {
431422
#handler = null;
432423
constructor(struct) {
@@ -694,7 +685,7 @@ class TypeHandler extends ErrorManager {
694685
break;
695686
}
696687
}
697-
if(this.#rng_fmt !== null) {
688+
if(valid && this.#rng_fmt !== null) {
698689
for(let rf of this.#rng_fmt) {
699690
[valid, val] = rf.exec(val);
700691
if(!valid) {

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@
66
"email": "[email protected]"
77
},
88
"license": "MIT",
9-
"version": "1.0"
9+
"version": "1.1"
1010
}

0 commit comments

Comments
 (0)