Introducció
Validating user input can be quite cumbersome from time to time, especially with predefined select values. Your back-end is expecting a predefined set of values and you should validate them both in your front-end as well as your back-end.
Instead of having your data validation and sanitization logic written as lengthy code, you can declare the requirements to your data with concise, easy to read and cross-platform JSON Schema or JSON Type Definition specifications and validate the data as soon as it arrives to your application.
TypeScript users can use validation functions as type guards, having type level guarantee that if your data is validated - it is correct.
Basic data validation
Ajv takes a schema for your JSON data and converts it into a very efficient JavaScript code that validates your data according to the schema.
Instal.la ajv
:
> bun install ajv
To create a schema you can use JSON Type Definition
For example, to validate an object that has a required property "foo" (an integer number), an optional property "bar" (a string) and no other properties:
import Ajv from "ajv/dist/jtd"
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
const schema = {
properties: {
foo: {type: "int32"}
},
optionalProperties: {
bar: {type: "string"}
}
}
const validate = ajv.compile(schema)
const data = {
foo: 1,
bar: "abc"
}
const valid = validate(data)
if (!valid) console.log(validate.errors)
Ajv compiles schemas to functions and caches them in all cases (using the schema itself as a key in a Map), so that the next time the same schema object is used it won't be compiled again.
Exemple
type Person ={
name: string,
surname: string
}
const elena: Person = JSON.parse('{"username":"Elena"}')
console.log(elena) //
Si executes aquest codi funciona:
> bun .\test.ts
{
username: "Elena",
}
Typescript confia en tu 🙄.
Has de validar les dades:
import Ajv, {type JTDSchemaType} from "ajv/dist/jtd"
const ajv = new Ajv()
type Person = {
name: string,
surname: string
}
const schema: JTDSchemaType<Person> = {
properties: {
name: {type: "string"},
surname: {type: "string"}
}
}
const validate = ajv.compile(schema)
const elena: Person = JSON.parse('{"username":"Elena"}')
if (!validate(elena)) {
console.log("Error!")
} else {
console.log(elena)
}
TODO
- https://yidaotus.medium.com/using-yup-and-typescript-for-typesafe-select-validation-e9ee9d4bceec
- https://medium.com/@9haroon_dev/using-js-object-schemas-for-custom-validations-with-yup-zod-joi-and-more-c3eeccf5998c
- https://medium.com/@olivier.trinh/how-to-create-form-validation-with-yup-library-in-reactjs-4846f045957a