0.1.1 • Published 3 years ago

object-validation-pattern v0.1.1

Weekly downloads
858
License
MIT
Repository
github
Last release
3 years ago

Build Status Coverage Status

Object Validation Pattern

Usage

Create a DTO class

interface SignUpDTO {
    name: string
    email: string
    password: string
    confirmPassword: string
}

Create a validator for the DTO class

class SignUpValidator extends ObjectValidator<SignUpDTO> {
    constructor(state: ObjectState<SignUpDTO>) {
        super(state)
    }

    setRules(rules: RulesBuilder<SignUpDTO>): void { 
        rules
            .add("name")
            .isString()
            .notEmpty()
            .breakChain()
            .minLength(3)
            .maxLength(10)
            .breakChain()
            .checkAsync(async (_, __, name) => 
                !(await userService.userExists(name)),
                "$name: The user $value already exists")

        rules
            .add("email")
            .isString()
            .notEmpty()
            .breakChain()
            .isEmail()
        
        rules
            .add("password")
            .isString()
            .notEmpty()

        rules
            .add("confirmPassword")
            .isString()
            .notEmpty()
            .breakChain()
            .compareWithField("password", "equal", 
                "The password and the confirm password fields are not same")
           
    }
}

Create an instance is implemented by the SignUpDTO interface and define the StateObject and the Validator instances

const model = {
    name: "User name",
    email: "username@someexampleserver.com",
    password: "password",
    confirmPassword: "passw0rd"
}

const modelState = new StateObject<SignUpDTO>()
const validator = new SignUpValidator(modelState)

Execute somewhere in a code

async function validate() {
    await validator.validate(model) 

    /*
    * or for the the field you can use 
    * await validator.validateField(model, "confirmPassword")
    */

    console.log(modelState.isValid) 
    console.log(modelState.items) 
}

Output:

false
[
    "confirmPassword": [
        ...
        { 
            "valid": false, 
            "text": "The password and the confirm password fields are not same"
        }
    ]
]

Custom validation extension

  1. use an import "object-validator-pattern/lib/extensions"
  2. How can I do custom validation extension
0.1.1

3 years ago

0.1.0

3 years ago

0.0.21

3 years ago

0.0.20

3 years ago

0.0.16

3 years ago

0.0.17

3 years ago

0.0.18

3 years ago

0.0.19

3 years ago

0.0.14

3 years ago

0.0.15

3 years ago

0.0.13

3 years ago

0.0.12

3 years ago

0.0.10

3 years ago

0.0.11

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago