Created
June 26, 2018 14:46
-
-
Save wbarcovsky/6d7106ed93dfc6ee5bcdbbe0af4bab23 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {object, string, number, Schema } from 'yup'; | |
| interface Hash { | |
| [p: string]: string; | |
| } | |
| class FormSchema { | |
| constructor(protected schema: Schema<any>) {} | |
| protected _errors: Hash = {}; | |
| public get errors() { return this._errors; } | |
| validate(data): boolean { | |
| this._errors = {}; | |
| try { | |
| this.schema.validateSync(data, { abortEarly: false }); | |
| } catch (e) { | |
| e.inner.forEach(oneError => { | |
| if (!this._errors[oneError.path]) { | |
| this._errors[oneError.path] = oneError.message; | |
| } | |
| }); | |
| } | |
| return Object.keys(this._errors).length === 0; | |
| } | |
| } | |
| async function main() { | |
| const form = new FormSchema(object({ | |
| name: string().required(), | |
| age: number().required().positive().integer(), | |
| email: string().email(), | |
| website: string().url(), | |
| })); | |
| const contact = { | |
| name: 'test', | |
| age: -100, | |
| email: 'asdasd' | |
| }; | |
| console.log(form.validate(contact)); | |
| // false | |
| console.log(form.errors); | |
| // { age: 'age must be a positive number', email: 'email must be a valid email' } | |
| contact.email = '[email protected]'; | |
| contact.age = 10; | |
| console.log(form.validate(contact)); | |
| // true | |
| }; | |
| main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment