Code Monkey home page Code Monkey logo

v4f's Introduction

undefined undefined undefined

Documentation | Exemples | API Reference | Need help ?

Description

A javascript library for validation that encourages rapid development and clean code, unlike other validation libraries v4f is designed from the ground up to be adaptable for any context, and it takes care of all your validation in different environments (client, server, native).

You can use V4f together with (react.js, angular.js, vue.js, jquery) or with any web framework.

Why

why new validation library where they exist several good ones around, sure you are completely right. but the problem with those libraries is that almost all of the theme focus in data validation and they forget the key reason why we do validation for, is that we desire to guide our users by showing them what they missing or what they doing wrong with some pieces of information, but sadly you end up with generic messages errors or writing code on the top of this libraries every time you use them.

V4F comes to solve this problem by focusing on those two features validations and failures messages, V4F comes with easy and powerful syntax that feels more human that everyone can understand with more than 40+ built-in rules.

Out of the box

  • Schema : v4f use the concept of the schema types to indicate your rules that will be checked later were we need it, this notion is powerful it lets you create complex rules ones and use it multiple types.

  • Nested schema : with v4f you can use a schema that already created inside other schemas to create complex validation.

  • Related field : validate fields that related or depends on each other easily with a simple syntax.

  • Single field : Validate only one field from schema very useful in situations like instead field validation feedback.

  • Async-sync : Validate your schema in asynchronous or synchronous way.

Getting started

Syntax overview

import { Schema, Field } from "v4f";

const User = Schema({
 username: Field()
  .string()
  .alphaNum()
  .required(),
 email: Field()
  .string()
  .email()
  .required(),
 password: Field()
  .string()
  .min(6)
  .max(20)
  .not.equals(["#username"])
  .not.equals(["#email"])
  .required(),
 cPassword: Field()
  .string()
  .equals(["#password"])
  .required()
});

const result = User.validate(data);

The above schema defines the following constraints:

  • username :
    • Must be string
    • Must be alpha numeric
    • Required
  • email :
    • Must be string
    • Must be valid email
    • Required
  • password :
    • Must be string
    • At least 6 characters long but no more than 20
    • Must not be equals to username and email
    • Required
  • cPassword :
    • Must be string
    • Must equals to password
    • Required

Instalation

To install the stable version:

$ npm install v4f

This assumes you are using npm as your package manager.

or

$ yarn add v4f

If you you use yarn as package your package manager.

Usage

Commonjs

var v4f = required("v4f");

const User = v4f.Schema({// Your schema here});

ES6

import {Schema, Field} from "v4f";

const User = Schema({// Your schema here});

Read the Usage Guide on our website for detailed instructions on how to use the library.

Rule Reference

Contributing

In general, we follow the "fork-and-pull" Git workflow.

  1. Fork on GitHub
  2. Make changes to your own fork
  3. Submit a Pull request so that we can review your changes

Test

$ yarn test

Linter

$ yarn lint

Maintainers

  • reyx7 - Nassih Soufiane (author)

License (MIT)

MIT License

Copyright (c) 2019 soufiane nassih [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

v4f's People

Contributors

nsoufian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

v4f's Issues

Add When object for cross-field validation

Implement cross-field validation by adding new Type When that will be added in rules options to declare the condition for that rule.

simple When

example :

import {Field, Schema, When} from "v4f";

const Server = Schema({
host: Field().string().required(),
user: Field().string().required(),
sudo: Field().boolean().truly({
  when: When('user', Field().string().notEqual('root'))
})
});

Boolean sudo must be true when user field is not root.

When with multiple conditition

import {Field, Schema, When} from "v4f";
const User = Schema({
username: Field().string().required(),
password: Field().string().required(),
isAdmin: Field().boolean().optional(),
isActive: Field().boolean().required(),
adminUrl: Field().string().url().required({when:
When('isAdmin',Field().boolean().truly()).end('isActive': Field().boolean().truly())
 })
});

adminUrl field is required when isAdmin is true and isActive is true

Implement SchemaType object to create schema validator

Implement SchemaType Object that will Be Exported as default to create validator schema,
The syntax must be like this examples :

Data to validate :

const user = {
  username: "reyx",
  password: "mypass",
  session: false,
}

Simple Schema

Create Simple Schema for user with no messages:

import SchemaType , {field} from "v4f";
const UserSchemaSimple = SchemaType({
 username: field().string().minLength(6).maxLength(20).requierd(),
 password: field().string().minLegnth(6).maxLength(30).required(),
 session: field().boolean().optional()
});

Schema wtih erros message

import SchemaType , {field} from "v4f";
const UserSchemaMessage = SchemaType({
 username: field()
  .string({message:"Username field must be string"})
  .minLength(6,{message:"Username field must have 6 characters min length"})
  .maxLength(20, {message:"Username field must have 20 characters max length"})
  .requierd({message:"Username field is required"}),
 password: field()
  .string({message:"Password field must be string"})
  .minLegnth(6,{message:"Password field must have 6 characters min length"})
  .maxLength(30, {message:"Password field must have 20 characters max length"})
  .required({message:"Password field is required"}),
 session: field().
  boolean()
  .optional()
});

Nessted Schema

nessted Schema syntax exemple:

const AdminUesr = Schematype({
isAdmin: field().
  boolean()
 .truthly(),
user: User
}) 

Validation

Simple validation with boolean resulte :

const errors = UserSchemaSimple.validate(user);
/**
 error object with containe false because validation faild in 
 username min length
**/

Validation with object errors contains messages:

const errors = UserSchemaMessage.validate(user, {message: true});
/**
 erros objects contain : 
{
  username: "Username field must have 6 characters min length"
}
If  validation success will contain null.
**/

Validate Only one field of the schema:

 const usernameError = UserSchemaMessage.username("myusername", {message: true});
/**
  usernameError will contain null validation success
**/

Fix access to nested value in When

When with nested field name not work

example

import {When, Field} from "v4f";
const username = Field()
  .string()
  .required({
    when: When(
      "address.zipCode",
      Field()
        .string()
        .required()
    )
  });

Implement Rule validation with cross field data

exemple :

import {Schema, Field, When} from "v4f";

const User = Schema({
username: Field()
 .string()
 .required();
email: Field()
 .string()
 .required();
password:Field()
 .string()
 .notEquals(["#username"])
 .required();
passwordConfirmation:Field()
 .string()
 .equals(["#password"])
 .required();
});

Passing related field's value in custom function

Lately I've been wondering and trying to make custom function that could use value of some other related field.

I'm fine using custom validators in custom(), but can't figure out if it's possible to pass

["#someField"]

inside that custom validator, like

Field().custom(someNotYetWorkingValidator(["#someField"]))

To be more precise - I have two datepickers in my form and would like to validate their dates (later/earlier etc.)

I'm not experienced in js, but looking at source code, it doesn't seem to be possible just because how custom() is written.

export const custom = (fun, value) => fun(value);

Could you provide me with some tips? (i've been thinking about forking and trying to add some additional lines, but maybe I'm missing some existing solution)

Add multiple field names to When

Accept multiple field names as an array for When to check the same rule for multiple fields:

example :

import {Schema, Field, When} from "v4f";

const User = Schema({
  username: Field()
    .string()
    .required(),
  isAdmin: Field()
    .boolean()
    .required(),
  isActive: Field()
    .boolean()
    .required(),
  url: Field()
    .string()
    .required({
      when: When(
        ["isAdmin", "isActive"],
        Field()
          .boolean()
          .truthy()
      )
        .or(
          "username",
          Field()
            .string()
            .notEquals("admin")
        )
    })
});
});

Is there a way to do async username checks? [Question]

I see I can do an async check. I'm just unsure how to insert a method into the username field of my signup screen to have it fail if the username doesn't work. Is this possible to do with v4f?

My schema:

const SignUpValidator = Schema(
    {
        email: Field()
            .string()
            .email({ message: "Not an e-mail address" })
            .required({ message: "E-mail is required" }),
        firstName: Field()
            .string()
            .required({ message: "First name is required." }),
        lastName: Field()
            .string()
            .required({ message: "Last name is required."}),
        password: Field()
            .string()
            .not.equals(['#email'], { message: "Password cannot be the same as email" })
            .min(8, { message: "Password must be at least 8 characters" })
            .max(64, { message: "Password cannot be longer than 64 characters" })
            .required({ message: "Password is required" }),
        cpassword: Field()
            .equals(['#password'], { message: "Confirmation password must match password." })
            .required({ message: "Password is required" })
    },
    { verbose: true, async: true }
    // We set the options on creation all call to Schema Product will be verbose and async
);

Improve and Refactor code base

Refactor and improve the code base :

  • Refactor
  • Clean code
  • Comments
  • Functional Programming
  • Clean and Clear Test suites
  • Coverage and Find messing cases

Create Examples

  • React.js from example
  • Vue.js from example
  • Angular.js from example

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.