0.1.1 • Published 5 years ago
object-validation-pattern v0.1.1
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
- use an import "object-validator-pattern/lib/extensions"
- How can I do custom validation extension
0.1.1
5 years ago
0.1.0
5 years ago
0.0.21
5 years ago
0.0.20
5 years ago
0.0.16
5 years ago
0.0.17
5 years ago
0.0.18
5 years ago
0.0.19
5 years ago
0.0.14
5 years ago
0.0.15
5 years ago
0.0.13
5 years ago
0.0.12
5 years ago
0.0.10
5 years ago
0.0.11
5 years ago
0.0.9
5 years ago
0.0.8
5 years ago
0.0.7
5 years ago
0.0.6
5 years ago
0.0.5
5 years ago
0.0.4
5 years ago
0.0.3
5 years ago
0.0.2
5 years ago
0.0.1
5 years ago