object-validation-pattern
v0.1.1
Published
DTO entities validator
Downloads
4
Maintainers
Readme
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: "[email protected]",
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
- use an import "object-validator-pattern/lib/extensions"
- How can I do custom validation extension