object-validation-pattern

DTO entities validator

Usage no npm install needed!

<script type="module">
  import objectValidationPattern from 'https://cdn.skypack.dev/object-validation-pattern';
</script>

README

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) {
        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()
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