Idris Brhane

Idris Brhane

1601601660

Json Validator for Node and Deno

SimpleJsonValidator

Json Validator for NodeJS with simple ruby-like syntax

Installation

You can install this library using npm:

npm i --save simplejsonvalidator

Usage

First you need to create a new JsonValidator instance calling to exported function:

const jsonValidator = require('simplejsonvalidator');
const validator = jsonValidator();

Then, you can create validators using the ‘create’ method, which accepts a callback and the validator name

validator.create(t => ({
  user: t.string.required,  
  age: t.number,
  text: t.string.max(10).required,
}), 'validatorName');

Finally, you can validate any json using ‘validate’ function:

const json = {
  user: 'user',  
  age: 22,
  text: '123456789',
};
validator.validate(json, 'validatorName');

You can also nest objects like this:

validator.create(t => ({
  user: t.string.required,
  age: t.number,
  text: t.string.max(10).required,
  data: {
    token: t.string,
  },
}), 'demoValidator');

Types

String

Validates if type is string. Example:

validator.create(t => ({
  key: t.string,
}));

You can use this validators in string type:

Validator Explanation Example
required makes key required t.string.required
shouldBe checks if the values matches t.string.shouldBe(‘apples’, ‘oranges’)
max(number) maximum limit t.string.max(10)
min(number) minimum limit t.string.min(1)
matches(regex) tests if string matches regex t.string.matches(/Regex/)

Number

Validates if type is number. Example:

validator.create(t => ({
  key: t.number,
}));

You can use this validators in number type:

Validator Explanation Example
required makes key required t.number.required
shouldBe checks if the values matches t.number.shouldBe(22, 21)
positive checks if number is positive t.number.positive
negative checks if number is negative t.number.negative

Boolean

Validates if type is boolean. Example:

validator.create(t => ({
  key: t.boolean,
}));

You can use this validators in boolean type:

Validator Explanation Example
required makes key required t.boolean.required
shouldBe checks if the value matches t.boolean.shouldBe(false)

Array

Validates if type is array. Example:

validator.create(t => ({
  key: t.array,
}));

You can use this validators in array type:

Validator Explanation Example
required makes key required t.array.required
shouldBe checks if the values matches t.array.shouldBe([22, 21], [1, ‘hi’])
exactLength(number) check if array length is exactly the specified length t.array.exactLength(20)
lengthLowerTo(number) check if array length is lower to the specified length t.array.lengthLowerTo(9)
lengthUpperTo(number) check if array length is upper to the specified length t.array.lengthUpperTo(1)
notEmpty check if array legnth is not empty t.array.notEmpty

Date

Validates if type is date. Example:

validator.create(t => ({
  key: t.date,
}));

You can use this validators in date type:

Validator Explanation Example
required makes key required t.date.required
shouldBe checks if the values matches t.date.shouldBe(new Date())
beforeDate(Date) check if the date is before desired date t.date.beforeDate(new Date())
afterDate(Date) check if the date is after desired date t.date.afterDate(new Date())

Express Framework Integration

You can use our middleware with express to check jsons. You can do it calling to createMiddleware function to create a middleware:

validator.create(t => ({
  user: t.string.required,  
  age: t.number,
  text: t.string.max(10).required,
}), 'name');

app.post('/', validator.createMiddleware('name'), (req, res) => res.send(req.body););

By default, the middleware, when a json is not valid, returns this json with html status code 400:

{ status: 400, message: 'invalid json' }

You can customize this passing to createMiddleware your json and the status code:

const json = {
  error: 'bad json',
};
const middleware = validator.createMiddleware('validator name', json, 401);

Download Details:

Author: deltegui

Source Code: https://github.com/deltegui/SimpleJsonValidator

#deno #nodejs #node #javascript

What is GEEK

Buddha Community

Json Validator for Node and Deno
Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Idris Brhane

Idris Brhane

1601601660

Json Validator for Node and Deno

SimpleJsonValidator

Json Validator for NodeJS with simple ruby-like syntax

Installation

You can install this library using npm:

npm i --save simplejsonvalidator

Usage

First you need to create a new JsonValidator instance calling to exported function:

const jsonValidator = require('simplejsonvalidator');
const validator = jsonValidator();

Then, you can create validators using the ‘create’ method, which accepts a callback and the validator name

validator.create(t => ({
  user: t.string.required,  
  age: t.number,
  text: t.string.max(10).required,
}), 'validatorName');

Finally, you can validate any json using ‘validate’ function:

const json = {
  user: 'user',  
  age: 22,
  text: '123456789',
};
validator.validate(json, 'validatorName');

You can also nest objects like this:

validator.create(t => ({
  user: t.string.required,
  age: t.number,
  text: t.string.max(10).required,
  data: {
    token: t.string,
  },
}), 'demoValidator');

Types

String

Validates if type is string. Example:

validator.create(t => ({
  key: t.string,
}));

You can use this validators in string type:

Validator Explanation Example
required makes key required t.string.required
shouldBe checks if the values matches t.string.shouldBe(‘apples’, ‘oranges’)
max(number) maximum limit t.string.max(10)
min(number) minimum limit t.string.min(1)
matches(regex) tests if string matches regex t.string.matches(/Regex/)

Number

Validates if type is number. Example:

validator.create(t => ({
  key: t.number,
}));

You can use this validators in number type:

Validator Explanation Example
required makes key required t.number.required
shouldBe checks if the values matches t.number.shouldBe(22, 21)
positive checks if number is positive t.number.positive
negative checks if number is negative t.number.negative

Boolean

Validates if type is boolean. Example:

validator.create(t => ({
  key: t.boolean,
}));

You can use this validators in boolean type:

Validator Explanation Example
required makes key required t.boolean.required
shouldBe checks if the value matches t.boolean.shouldBe(false)

Array

Validates if type is array. Example:

validator.create(t => ({
  key: t.array,
}));

You can use this validators in array type:

Validator Explanation Example
required makes key required t.array.required
shouldBe checks if the values matches t.array.shouldBe([22, 21], [1, ‘hi’])
exactLength(number) check if array length is exactly the specified length t.array.exactLength(20)
lengthLowerTo(number) check if array length is lower to the specified length t.array.lengthLowerTo(9)
lengthUpperTo(number) check if array length is upper to the specified length t.array.lengthUpperTo(1)
notEmpty check if array legnth is not empty t.array.notEmpty

Date

Validates if type is date. Example:

validator.create(t => ({
  key: t.date,
}));

You can use this validators in date type:

Validator Explanation Example
required makes key required t.date.required
shouldBe checks if the values matches t.date.shouldBe(new Date())
beforeDate(Date) check if the date is before desired date t.date.beforeDate(new Date())
afterDate(Date) check if the date is after desired date t.date.afterDate(new Date())

Express Framework Integration

You can use our middleware with express to check jsons. You can do it calling to createMiddleware function to create a middleware:

validator.create(t => ({
  user: t.string.required,  
  age: t.number,
  text: t.string.max(10).required,
}), 'name');

app.post('/', validator.createMiddleware('name'), (req, res) => res.send(req.body););

By default, the middleware, when a json is not valid, returns this json with html status code 400:

{ status: 400, message: 'invalid json' }

You can customize this passing to createMiddleware your json and the status code:

const json = {
  error: 'bad json',
};
const middleware = validator.createMiddleware('validator name', json, 401);

Download Details:

Author: deltegui

Source Code: https://github.com/deltegui/SimpleJsonValidator

#deno #nodejs #node #javascript

Node JS Server Side Form Validation using Express-Validator, Body-Parser and EJS

Today we are going to do some server-side form validation using the Express-validator, Body-parser and for the view engine, I will be using EJS.

This is an introduction video, but it should give you enough knowledge to get you started with form validation.

As you might already know it’s usually good practice to validate user input on Server Side because you can protect against malicious users, who can easily bypass your client-side scripting language and submit dangerous input to the server.

BLOG POST & SOURCE FILES
https://raddy.co.uk/blog/node-js-form-validation-using-express-validator-and-ejs/

Introduction: (0:00)
Project Overview: (1:00)
Views & Form: (3:20)
Form Validation: (9:34)
Outro: (20:37)

CONNECT with RaddyTheBrand
Website: https://www.raddy.co.uk
GitHub: https://www.github.com/RaddyTheBrand
Instagram: https://www.instagram.com/RaddyTheBrand
Twitter: https://www.twitter.com/RaddyTheBrand
Newsletter: https://www.raddy.co.uk/newsletter

DONATE to RaddyTheBrand
BuyMeACoffee: https://www.buymeacoffee.com/RaddyTheBrand
PayPal: https://bit.ly/3tAuElv

#ejs #node js #node #express-validator #body-parser #node js server side

Iterate over JSON with Root Node in JavaScript

A large portion of a frontend developer’s work includes working with JSON responses when integrating backend APIs in an app. JSON responses are often complex and difficult to comprehend in one go. However, their complex structure is justified in terms of demystifying the data returned to the frontend. Thus, you may receive a JSON response with a root node indicating what the corresponding object is about.

In this guide, you’ll learn how to identify and understand JSON responses with root nodes and eventually iterate over them using JavaScript in React.

#json #node #node

Deno Based JSON Format DB

Deno JSON DB

A simple DB based on Deno.

Notes

This module is a work in progress.
We are working on a pilot implementation of a module like NeDB.

If the feature you need is not present in the “Upcoming features”, please let us know what you want in Issue.

Feature

  • Deno Modules
  • Save in JSON format
  • The storage formats are in-memory and file

Upcoming features

  • [x] Write data
  • [x] Delete the specified data
  • [x] Return data that matches the condition
  • [x] Save the data as a file
  • [x] Asynchronous support
  • [ ] Partial search with regular expressions

API

When creating a file, you must add --allow-read and --allow-write at execution to read and write the file.

Create DB

The first argument is the DB type. If it is “file”, it is a file; if it is “memory”, it is managed in-memory.
The second argument is the DB path. If it is “file”, it will be an error if it is not written.

import { SimpleDB } from 'https://github.com/windchime-yk/deno-simple-db/raw/master/mod.ts'

interface DB {
  _id: string,
  name?: string
}

const db = new SimpleDB<DB>({
  type: 'file',
  folder: './db/',
})

Add an Object to the DB

The first argument is the Object to add to the DB.
The second argument is the key used in the duplication prevention process.

import { v4 } from 'https://deno.land/std@0.77.0/uuid/mod.ts';

const test = {
  _id: v4.generate(),
  name: 'Asomaka Toika'
}

await db.add(test, 'name')

Remove matching objects from DB

The first argument is the key, and the second argument is the value of the key.

await db.delete('name', 'Asomaka Toika')

Searching the DB

Returns an Object that matches the conditions, with the name of the key as the first argument and the value of the key as the second argument.
No arguments return all DB data.

const data = await db.find('name', 'Asomaka Toika')
const dataAll = await db.find()

Test

Execute the following command.

$ git clone git@github.com:windchime-yk/deno-simple-db.git
$ cd path/to/deno-simple-db

# If there is no Denon
$ deno run --allow-write --allow-read test.ts
# If you have a Denon
$ denon test

On translation

I am using “DeepL Translation” to translate this README.

Download Details:

Author: windchime-yk

Source Code: https://github.com/windchime-yk/deno-json-db

#deno #nodejs #node #javascript #json