npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

als-validator

v0.8.0

Published

Small class for frontend and backend fields validation

Downloads

4

Readme

Validator

About

Validator is a small JavaScript class for frontend and backend (node.js). The class validate if data inside object match the requirements.

v07 - change log

  1. Validator return object {errors:0,field:[errors]} insted array [errors]. Now each field gets it's errors and errors.errors counts the sum of errors (0 by default).
  2. Now you can add spaces to field in arror output by adding _ in variable name. For example answer_1:'required' will return The answer 1 can't be empty.

Example:

let data = {
    email:'[email protected]',
    password:'q6we4r%ty',
    url:'alex.com',
    json:'{"age":"20"}'
}

let obj = {
    email:'email',
    password:'min:7|required|symbols|nums:3',
    url:'url',
    json:'json'
}

let errors = new Validator(obj,data).run()
console.log(errors) // Output: {password:[0: "The password has to contain at least 3 number characters"]}

Validation rules

List of validation rules for run method

  • required - checks if field is empty or null
  • email - checks if field is an email
  • lowers:times - checks if field has lowercase characters * times
  • uppers:times - checks if field has uppercase characters * times
  • nums:times - checks if field has numeric characters * times
  • symbols:times - checks if field has special symbol characters * times
  • url - checks if field is an url
  • json - checks if field is a valid json
  • unique - checks if field has no repeated characters

Method which use the async method and model

  • confirm:field2 - checks if field's value = field2's value
  • exists:tableName - checks if field's value exist in given table in db
  • notexists:tableName - checks if field's value not exist in given table in db
  • password:tableName - checks if field's value matches value in given table in db
    • If req.data containes id, the match check will occure only at id
    • If req.data not containes id field, the match check will occure in all recordes in a table

Basics

Validator is a class and it's constructor gets two parameters: obj and data.

  • obj - is an object with ruels for validation
  • data - is an object with data for validation
  • model - model is an als-model object

The syntax:

let errors = new Validator(obj,data).run()
let errors = new Validator(obj,data,model).async()

The run method, runs loop for checking each field in obj and validate fields from data. If all fields pass validation, it returns empty array. Else, it returns array with errors.

data

Data has to be json with {field:value,field:value} format. Value has to be string.

obj

The object has to be with {field:rules,field:rules} format. The rules are separetad by | and parameter separated with :.

For example:

let data = {password:"aaa333$F"}
let obj = {password:"unique|num|uppers:2|symbols|required"}
let errors = new Validator(obj,data).run()
console.log(errors)

// The output:
// [
//     errors:2,
//     password: [
//         0: "The aaa333$F has repeated characters"
//         1: "The password has to contain at least 2 uppercase characters"
//     ]
// ]

The example above checking password field "aaa333$F" for:

  1. unique - repeated characters
  2. num - at least one numeric character
  3. apper:2 - at least two uppercase characters
  4. symbols - at least one special symbol character
  5. required - the field is not empty

Customize errors

All errors placed as functions inside Validator.$errors. There are two ways to customize errors:

  1. Go to node_modules\validate.js and change the error content to what ever you want
  2. Create new Validator object and then change the errors content on new object.$errors

Model and async method on node.js

To use model, you need to install als-model and create new model object with sqlite or mysql data base.

For example, you can do the folowing:

npm i als-model
const {join} = require('path')
let conData = join(__dirname,'db','data.sqlite3')

let model = new Model(conData)

Then you create the tables and migrate it, you can use this model with Validator async method.

async function auth() {
    let errors = await new Validator(obj,data,model).async()
}

form method and ajax validation

form method grabbing all input data (name:value) from input and select fields by listening to event.

form method has 3 parameters: id of form, event for listening and validation on loading page (false by default).

Syntax: form(formId,event,validateOnLoad = false)

  1. formId - id of form for grabbing the data
  2. event - any js event like input (oninput), change(onchange),..
  3. validateOnLoad - by default validation starts only if event occurs. By setting 3d parameter as true, you start validation on load too.

Errors:

In case of validation errors, you can publish them just by giving to element id with name of input field with addition of -error. For example if you have input field with name 'some' - <input type="text" name="some"> then element with id 'some-error' will get innerHtml = validationErrors.

<form action="/register" method="POST" id="register-form">
    <div><input class="input" type="email" name="email"></div>
    <small><div class="pl2 t-red" id="email-error"></div></small>

    <div><input class="input" type="text" name="username"></div>
    <small><div class="pl2 t-red" id="username-error"></div></small>

    <div><input class="input" type="password" name="password" id="password" ></div>
    <small><div class="pl2 t-red" id="password-error"></div></small>

    <div><input class="input" type="password" name="confirm" id="confirm"></div>
    <small><div class="pl2 t-red" id="confirm-error"></div></small>

    <button class="m2" type="submit" id="register">Register</button>
</form>

<script src="validate.js"></script>

<script>
    new Validator({
        email: 'email|ajax',
        confirm:'confirm:password',
        password: 'min:7|required|num',
        username: 'min:3'
    }).form('register-form','input',true)
</script>
if(isset($_SERVER['HTTP_AJAX'])) {
    // do some validation
    return json_encode($errors);
}

Ajax validation

For ajax validation, you need to install als-ajax.

If you put on any place of validation rules ajax, on every event, will be sent ajax request to server. The ajax request will be to form action and by form method.

After ajax validation, als-validator get response from server and trying to convert it to json. If json has names of fields, with errors array, errors are added to other errors.