├── .gitignore ├── .npmignore ├── .editorconfig ├── .babelrc ├── src ├── index.ts ├── printValue.ts ├── localeShort.ts ├── locale.ts └── localeForm.ts ├── tsconfig.json ├── .eslintrc.js ├── LICENSE ├── README.md ├── README.pt-br.md ├── package.json ├── jest.config.js └── tests ├── localeShort.spec.ts ├── localeForm.spec.ts └── locale.spec.ts /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .editorconfig 2 | .eslintrc.js 3 | tests 4 | jest.config.js 5 | src 6 | babel.config.js 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | end_of_line = lf 10 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", { 4 | "targets": { 5 | "node": "current" 6 | } 7 | }], 8 | "@babel/typescript" 9 | ], 10 | "plugins": [ 11 | "@babel/proposal-class-properties", 12 | "@babel/proposal-object-rest-spread" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import locale from './locale'; 2 | import localeForm from './localeForm'; 3 | import localeShort from './localeShort'; 4 | 5 | export const pt = locale; 6 | export const ptForm = localeForm; 7 | export const ptShort = localeShort; 8 | 9 | export default { 10 | pt, 11 | ptForm, 12 | ptShort, 13 | }; 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "lib": ["es2017", "es7", "es6", "dom"], 6 | "declaration": true, 7 | "emitDeclarationOnly": true, 8 | "isolatedModules": true, 9 | "outDir": "lib", 10 | "strict": true, 11 | "esModuleInterop": true 12 | }, 13 | "include": [ 14 | "src" 15 | ], 16 | "exclude": [ 17 | "node_modules", 18 | "lib" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: ['jest'], 3 | env: { 4 | es6: true, 5 | "jest/globals": true 6 | }, 7 | extends: [ 8 | 'airbnb-typescript/base', 9 | ], 10 | globals: { 11 | Atomics: 'readonly', 12 | SharedArrayBuffer: 'readonly', 13 | }, 14 | parserOptions: { 15 | ecmaVersion: 2018, 16 | sourceType: 'module', 17 | project: './tsconfig.json', 18 | }, 19 | rules: { 20 | 'no-template-curly-in-string': 'off' 21 | }, 22 | }; 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Antonio Roberto Furlaneto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Brazilian Portuguese Localization for Yup 2 | 3 | [Ler em Português](README.pt-br.md) 4 | 5 | ## Flavors 6 | There are three "flavors" of translation: 7 | - `pt` is the default translation of Yup's `locale.js` file. Example: *'name must be exactly 20 characters'*. 8 | - `ptForm` is optimized to be shown in form fields. It does not repeat the field name and is formatted like a sentence. Example: *'The field must be exactly 20 characters.'*. 9 | - `ptShort` is like `ptForm`, but shorter. Example: *'Must be exactly 20 characters.'* . 10 | 11 | ## Usage 12 | Install with npm ... 13 | ``` 14 | npm install yup-locale-pt 15 | ``` 16 | ... or with yarn ... 17 | ``` 18 | yarn add yup-locale-pt 19 | ``` 20 | ... and set locale with Yup's `setLocale`... 21 | ```js 22 | import * as Yup from 'yup'; 23 | import { pt } from 'yup-locale-pt'; 24 | 25 | Yup.setLocale(pt); 26 | ``` 27 | ...or... 28 | ```js 29 | import * as Yup from 'yup'; 30 | import { ptForm } from 'yup-locale-pt'; 31 | 32 | Yup.setLocale(ptForm); 33 | ``` 34 | ...or... 35 | ```js 36 | import * as Yup from 'yup'; 37 | import { ptShort } from 'yup-locale-pt'; 38 | 39 | Yup.setLocale(ptShort); 40 | ``` 41 | -------------------------------------------------------------------------------- /README.pt-br.md: -------------------------------------------------------------------------------- 1 | # Localização Português Brasileiro para o Yup 2 | 3 | [Read in English](README.md) 4 | 5 | ## Estilos 6 | Há três estilos de tradução: 7 | - `pt` é a tradução padrão do arquivo `locale.js` do Yup. Exemplo: *'nome deve ter exatamente 20 caracteres'* 8 | - `ptForm` é otimizado para ser exibido em campos de formulários. Ele não repete o nome do campo e é formatado como uma frase. Exemplo: *'O campo deve ter exatamente 20 caracteres.'* 9 | - `ptShort` é parecido com o `ptForm`, mas as mensagens são mais curtas. Exemplo: *'Deve ter exatamente 20 caracteres.'* 10 | 11 | ## Uso 12 | Instale com o npm ... 13 | ``` 14 | npm install yup-locale-pt 15 | ``` 16 | ... ou como o yarn ... 17 | ``` 18 | yarn add yup-locale-pt 19 | ``` 20 | e mude a localizaçao com a função `setLocale` do Yup... 21 | ```js 22 | import * as Yup from 'yup'; 23 | import { pt } from 'yup-locale-pt'; 24 | 25 | Yup.setLocale(pt); 26 | ``` 27 | ...ou... 28 | ```js 29 | import * as Yup from 'yup'; 30 | import { ptForm } from 'yup-locale-pt'; 31 | 32 | Yup.setLocale(ptForm); 33 | ``` 34 | ...ou... 35 | ```js 36 | import * as Yup from 'yup'; 37 | import { ptShort } from 'yup-locale-pt'; 38 | 39 | Yup.setLocale(ptShort); 40 | ``` 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yup-locale-pt", 3 | "version": "0.0.9", 4 | "description": "Brazilian Portuguese Localization for Yup", 5 | "main": "lib/index.js", 6 | "types": "lib/index.d.ts", 7 | "repository": { 8 | "type": "git", 9 | "url": "git:github.com/arfurlaneto/yup-locale-pt" 10 | }, 11 | "scripts": { 12 | "test": "jest", 13 | "build": "npm run build:types && npm run build:js", 14 | "build:types": "tsc --emitDeclarationOnly", 15 | "build:js": "babel src --out-dir lib --extensions \".ts\" --source-maps inline" 16 | }, 17 | "husky": { 18 | "hooks": { 19 | "prepare-commit-msg": "exec < /dev/tty && git cz --hook || true" 20 | } 21 | }, 22 | "config": { 23 | "commitizen": { 24 | "path": "cz-conventional-changelog" 25 | } 26 | }, 27 | "devDependencies": { 28 | "@babel/cli": "^7.8.4", 29 | "@babel/core": "^7.9.0", 30 | "@babel/plugin-proposal-class-properties": "^7.12.1", 31 | "@babel/plugin-proposal-object-rest-spread": "^7.12.1", 32 | "@babel/preset-env": "^7.12.11", 33 | "@babel/preset-typescript": "^7.12.7", 34 | "@types/jest": "^26.0.19", 35 | "@typescript-eslint/eslint-plugin": "4.4.1", 36 | "babel-jest": "^25.5.0", 37 | "commitizen": "^4.2.2", 38 | "cz-conventional-changelog": "^3.3.0", 39 | "eslint": "^6.8.0", 40 | "eslint-plugin-import": "2.20.1", 41 | "eslint-plugin-jest": "^23.8.2", 42 | "husky": "^4.3.6", 43 | "jest": "^25.5.0", 44 | "typescript": "^4.1.3", 45 | "yup": "^0.28.4" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/printValue.ts: -------------------------------------------------------------------------------- 1 | /* https://github.com/jquense/yup/blob/master/src/util/printValue.js */ 2 | 3 | /* eslint-disable eqeqeq */ 4 | /* eslint-disable no-restricted-globals */ 5 | /* eslint-disable func-names */ 6 | /* eslint-disable no-shadow */ 7 | 8 | const { toString } = Object.prototype; 9 | const errorToString = Error.prototype.toString; 10 | const regExpToString = RegExp.prototype.toString; 11 | const symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => ''; 12 | 13 | const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; 14 | 15 | function printNumber(val: any): string { 16 | if (val != +val) return 'NaN'; 17 | const isNegativeZero = val === 0 && 1 / val < 0; 18 | return isNegativeZero ? '-0' : `${val}`; 19 | } 20 | 21 | function printSimpleValue(val: any, quoteStrings: boolean = false): string | null { 22 | if (val == null || val === true || val === false) return `${val}`; 23 | 24 | const typeOf = typeof val; 25 | if (typeOf === 'number') return printNumber(val); 26 | if (typeOf === 'string') return quoteStrings ? `"${val}"` : val; 27 | if (typeOf === 'function') { return `[Function ${val.name || 'anonymous'}]`; } 28 | if (typeOf === 'symbol') { return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); } 29 | 30 | const tag = toString.call(val).slice(8, -1); 31 | if (tag === 'Date') { return isNaN(val.getTime()) ? `${val}` : val.toISOString(val); } 32 | if (tag === 'Error' || val instanceof Error) { return `[${errorToString.call(val)}]`; } 33 | if (tag === 'RegExp') return regExpToString.call(val); 34 | 35 | return null; 36 | } 37 | 38 | export default function printValue(value: any, quoteStrings: boolean): string { 39 | const result = printSimpleValue(value, quoteStrings); 40 | if (result !== null) return result; 41 | 42 | return JSON.stringify( 43 | value, 44 | function (key: string, value: any) { 45 | const result = printSimpleValue(this[key], quoteStrings); 46 | if (result !== null) return result; 47 | return value; 48 | }, 49 | 2, 50 | ); 51 | } 52 | -------------------------------------------------------------------------------- /src/localeShort.ts: -------------------------------------------------------------------------------- 1 | import printValue from './printValue'; 2 | 3 | export const mixed = { 4 | default: 'Inválido.', 5 | required: 'Obrigatório.', 6 | oneOf: 'Deve ter um dos seguintes valores: ${values}.', 7 | notOneOf: 'Não deve ter nenhum dos seguintes valores: ${values}.', 8 | notType: ({ 9 | type, value, originalValue, 10 | }: any) => { 11 | const isCast = originalValue != null && originalValue !== value; 12 | let msg = `${`Deve ser do tipo \`${type}\`, ` 13 | + `mas o valor final é: \`${printValue(value, true)}\``}${ 14 | isCast 15 | ? ` (cast do valor \`${printValue(originalValue, true)}\`).` 16 | : '.'}`; 17 | 18 | if (value === null) { 19 | msg += '\nSe a intenção era usar "null" como um valor em branco marque o esquema como `.nullable()`.'; 20 | } 21 | 22 | return msg; 23 | }, 24 | defined: 'Não deve ser indefinido.', 25 | }; 26 | 27 | export const string = { 28 | length: ({ length }: any) => `Deve ter exatamente ${length} ${length === 1 ? 'caractere' : 'caracteres'}.`, 29 | min: ({ min }: any) => `Deve ter pelo menos ${min} ${min === 1 ? 'caractere' : 'caracteres'}.`, 30 | max: ({ max }: any) => `Deve ter no máximo ${max} ${max === 1 ? 'caractere' : 'caracteres'}.`, 31 | matches: 'Deve corresponder ao padrão: "${regex}".', 32 | email: 'Deve ser um e-mail válido.', 33 | url: 'Deve ser uma URL válida.', 34 | trim: 'Não deve conter espaços adicionais no início nem no fim.', 35 | lowercase: 'Deve estar em letras minúsculas.', 36 | uppercase: 'Deve estar em letras maiúsculas.', 37 | }; 38 | 39 | export const number = { 40 | min: 'Deve ser maior ou igual a ${min}.', 41 | max: 'Deve ser menor ou igual a ${max}.', 42 | lessThan: 'Deve ser menor que ${less}.', 43 | moreThan: 'Deve ser maior que ${more}.', 44 | notEqual: 'Não deve ser igual a ${notEqual}.', 45 | positive: 'Deve ser um número positivo.', 46 | negative: 'Deve ser um número negativo.', 47 | integer: 'Deve ser um número inteiro.', 48 | }; 49 | 50 | export const date = { 51 | min: 'Deve ser posterior a ${min}.', 52 | max: 'Deve ser anterior a ${max}.', 53 | }; 54 | 55 | export const boolean = {}; 56 | 57 | export const object = { 58 | noUnknown: 'Existem chaves desconhecidas: ${unknown}.', 59 | }; 60 | 61 | export const array = { 62 | min: ({ min } : any) => `Deve ter pelo menos ${min} ${min === 1 ? 'item': 'itens'}.`, 63 | max: ({ max } : any) => `Deve ter no máximo ${max} ${max === 1 ? 'item': 'itens'}.`, 64 | }; 65 | 66 | export default { 67 | mixed, 68 | string, 69 | number, 70 | date, 71 | object, 72 | array, 73 | boolean, 74 | }; 75 | -------------------------------------------------------------------------------- /src/locale.ts: -------------------------------------------------------------------------------- 1 | import printValue from './printValue'; 2 | 3 | export const mixed = { 4 | default: '${path} é inválido', 5 | required: '${path} é obrigatório', 6 | oneOf: '${path} deve ter um dos seguintes valores: ${values}', 7 | notOneOf: '${path} não deve ter nenhum dos seguintes valores: ${values}', 8 | notType: ({ 9 | path, type, value, originalValue, 10 | }: any) => { 11 | const isCast = originalValue != null && originalValue !== value; 12 | let msg = `${`${path} deve ser do tipo \`${type}\`, ` 13 | + `mas o valor final é: \`${printValue(value, true)}\``}${ 14 | isCast 15 | ? ` (cast do valor \`${printValue(originalValue, true)}\`)` 16 | : ''}`; 17 | 18 | if (value === null) { 19 | msg += '\nse a intenção era usar "null" como um valor em branco marque o esquema como `.nullable()`'; 20 | } 21 | 22 | return msg; 23 | }, 24 | defined: '${path} não deve ser indefinido', 25 | }; 26 | 27 | export const string = { 28 | length: ({ path, length }: any) => `${path} deve ter exatamente ${length} ${length === 1 ? 'caractere' : 'caracteres'}`, 29 | min: ({ path, min }: any) => `${path} deve ter pelo menos ${min} ${min === 1 ? 'caractere' : 'caracteres'}`, 30 | max: ({ path, max }: any) => `${path} deve ter no máximo ${max} ${max === 1 ? 'caractere' : 'caracteres'}`, 31 | matches: '${path} deve corresponder ao padrão: "${regex}"', 32 | email: '${path} deve ser um e-mail válido', 33 | url: '${path} deve ser uma URL válida', 34 | trim: '${path} não deve conter espaços adicionais no início nem no fim', 35 | lowercase: '${path} deve estar em letras minúsculas', 36 | uppercase: '${path} deve estar em letras maiúsculas', 37 | }; 38 | 39 | export const number = { 40 | min: '${path} deve ser maior ou igual a ${min}', 41 | max: '${path} deve menor ou igual a ${max}', 42 | lessThan: '${path} deve ser menor que ${less}', 43 | moreThan: '${path} deve ser maior que ${more}', 44 | notEqual: '${path} não deve ser igual a ${notEqual}', 45 | positive: '${path} deve ser um número positivo', 46 | negative: '${path} deve ser um número negativo', 47 | integer: '${path} deve ser um número inteiro', 48 | }; 49 | 50 | export const date = { 51 | min: '${path} deve ser posterior a ${min}', 52 | max: '${path} deve ser anterior a ${max}', 53 | }; 54 | 55 | export const boolean = {}; 56 | 57 | export const object = { 58 | noUnknown: '${path} tem chaves desconhecidas: ${unknown}', 59 | }; 60 | 61 | export const array = { 62 | min: ({ path, min }: any) => `${path} deve ter pelo menos ${min} ${min === 1 ? 'item' : 'itens'}`, 63 | max: ({ path, max }: any) => `${path} deve ter no máximo ${max} ${max === 1 ? 'item' : 'itens'}`, 64 | }; 65 | 66 | export default { 67 | mixed, 68 | string, 69 | number, 70 | date, 71 | object, 72 | array, 73 | boolean, 74 | }; 75 | -------------------------------------------------------------------------------- /src/localeForm.ts: -------------------------------------------------------------------------------- 1 | import printValue from './printValue'; 2 | 3 | export const mixed = { 4 | default: 'O campo é inválido.', 5 | required: 'O campo é obrigatório.', 6 | oneOf: 'O campo deve ter um dos seguintes valores: ${values}.', 7 | notOneOf: 'O campo não deve ter nenhum dos seguintes valores: ${values}.', 8 | notType: ({ 9 | type, value, originalValue, 10 | }: any) => { 11 | const isCast = originalValue != null && originalValue !== value; 12 | let msg = `${`O campo deve ser do tipo \`${type}\`, ` 13 | + `mas o valor final é: \`${printValue(value, true)}\``}${ 14 | isCast 15 | ? ` (cast do valor \`${printValue(originalValue, true)}\`).` 16 | : '.'}`; 17 | 18 | if (value === null) { 19 | msg += '\nSe a intenção era usar "null" como um valor em branco marque o esquema como `.nullable()`.'; 20 | } 21 | 22 | return msg; 23 | }, 24 | defined: 'O campo não deve ser indefinido.', 25 | }; 26 | 27 | export const string = { 28 | length: ({ length }: any) => `O campo deve ter exatamente ${length} ${length === 1 ? 'caractere' : 'caracteres'}.`, 29 | min: ({ min }: any) => `O campo deve ter pelo menos ${min} ${min === 1 ? 'caractere' : 'caracteres'}.`, 30 | max: ({ max }: any) => `O campo deve ter no máximo ${max} ${max === 1 ? 'caractere' : 'caracteres'}.`, 31 | matches: 'O campo deve corresponder ao padrão: "${regex}".', 32 | email: 'O campo deve ser um e-mail válido.', 33 | url: 'O campo deve ser uma URL válida.', 34 | trim: 'O campo não deve conter espaços adicionais no início nem no fim.', 35 | lowercase: 'O campo deve estar em letras minúsculas.', 36 | uppercase: 'O campo deve estar em letras maiúsculas.', 37 | }; 38 | 39 | export const number = { 40 | min: 'O campo deve ser maior ou igual a ${min}.', 41 | max: 'O campo deve menor ou igual a ${max}.', 42 | lessThan: 'O campo deve ser menor que ${less}.', 43 | moreThan: 'O campo deve ser maior que ${more}.', 44 | notEqual: 'O campo não deve ser igual a ${notEqual}.', 45 | positive: 'O campo deve ser um número positivo.', 46 | negative: 'O campo deve ser um número negativo.', 47 | integer: 'O campo deve ser um número inteiro.', 48 | }; 49 | 50 | export const date = { 51 | min: 'O campo deve ser posterior a ${min}.', 52 | max: 'O campo deve ser anterior a ${max}.', 53 | }; 54 | 55 | export const boolean = {}; 56 | 57 | export const object = { 58 | noUnknown: 'O campo tem chaves desconhecidas: ${unknown}.', 59 | }; 60 | 61 | export const array = { 62 | min: ({ min }: any) => `O campo deve ter pelo menos ${min} ${min === 1 ? 'item': 'itens'}.`, 63 | max: ({ max }: any) => `O campo deve ter no máximo ${max} ${max === 1 ? 'item': 'itens'}.`, 64 | }; 65 | 66 | export default { 67 | mixed, 68 | string, 69 | number, 70 | date, 71 | object, 72 | array, 73 | boolean, 74 | }; 75 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-len */ 2 | 3 | // For a detailed explanation regarding each configuration property, visit: 4 | // https://jestjs.io/docs/en/configuration.html 5 | 6 | module.exports = { 7 | // All imported modules in your tests should be mocked automatically 8 | // automock: false, 9 | 10 | // Stop running tests after `n` failures 11 | // bail: 0, 12 | 13 | // Respect "browser" field in package.json when resolving modules 14 | // browser: false, 15 | 16 | // The directory where Jest should store its cached dependency information 17 | // cacheDirectory: "C:\\Users\\arfurlaneto\\AppData\\Local\\Temp\\jest", 18 | 19 | // Automatically clear mock calls and instances between every test 20 | clearMocks: true, 21 | 22 | // Indicates whether the coverage information should be collected while executing the test 23 | // collectCoverage: false, 24 | 25 | // An array of glob patterns indicating a set of files for which coverage information should be collected 26 | // collectCoverageFrom: undefined, 27 | 28 | // The directory where Jest should output its coverage files 29 | coverageDirectory: 'coverage', 30 | 31 | // An array of regexp pattern strings used to skip coverage collection 32 | // coveragePathIgnorePatterns: [ 33 | // "\\\\node_modules\\\\" 34 | // ], 35 | 36 | // A list of reporter names that Jest uses when writing coverage reports 37 | // coverageReporters: [ 38 | // "json", 39 | // "text", 40 | // "lcov", 41 | // "clover" 42 | // ], 43 | 44 | // An object that configures minimum threshold enforcement for coverage results 45 | // coverageThreshold: undefined, 46 | 47 | // A path to a custom dependency extractor 48 | // dependencyExtractor: undefined, 49 | 50 | // Make calling deprecated APIs throw helpful error messages 51 | // errorOnDeprecated: false, 52 | 53 | // Force coverage collection from ignored files using an array of glob patterns 54 | // forceCoverageMatch: [], 55 | 56 | // A path to a module which exports an async function that is triggered once before all test suites 57 | // globalSetup: undefined, 58 | 59 | // A path to a module which exports an async function that is triggered once after all test suites 60 | // globalTeardown: undefined, 61 | 62 | // A set of global variables that need to be available in all test environments 63 | // globals: {}, 64 | 65 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 66 | // maxWorkers: "50%", 67 | 68 | // An array of directory names to be searched recursively up from the requiring module's location 69 | // moduleDirectories: [ 70 | // "node_modules" 71 | // ], 72 | 73 | // An array of file extensions your modules use 74 | // moduleFileExtensions: [ 75 | // "js", 76 | // "json", 77 | // "jsx", 78 | // "ts", 79 | // "tsx", 80 | // "node" 81 | // ], 82 | 83 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 84 | // moduleNameMapper: {}, 85 | 86 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 87 | // modulePathIgnorePatterns: [], 88 | 89 | // Activates notifications for test results 90 | // notify: false, 91 | 92 | // An enum that specifies notification mode. Requires { notify: true } 93 | // notifyMode: "failure-change", 94 | 95 | // A preset that is used as a base for Jest's configuration 96 | // preset: undefined, 97 | 98 | // Run tests from one or more projects 99 | // projects: undefined, 100 | 101 | // Use this configuration option to add custom reporters to Jest 102 | // reporters: undefined, 103 | 104 | // Automatically reset mock state between every test 105 | // resetMocks: false, 106 | 107 | // Reset the module registry before running each individual test 108 | // resetModules: false, 109 | 110 | // A path to a custom resolver 111 | // resolver: undefined, 112 | 113 | // Automatically restore mock state between every test 114 | // restoreMocks: false, 115 | 116 | // The root directory that Jest should scan for tests and modules within 117 | // rootDir: undefined, 118 | 119 | // A list of paths to directories that Jest should use to search for files in 120 | // roots: [ 121 | // "" 122 | // ], 123 | 124 | // Allows you to use a custom runner instead of Jest's default test runner 125 | // runner: "jest-runner", 126 | 127 | // The paths to modules that run some code to configure or set up the testing environment before each test 128 | // setupFiles: [], 129 | 130 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 131 | // setupFilesAfterEnv: [], 132 | 133 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 134 | // snapshotSerializers: [], 135 | 136 | // The test environment that will be used for testing 137 | testEnvironment: 'node', 138 | 139 | // Options that will be passed to the testEnvironment 140 | // testEnvironmentOptions: {}, 141 | 142 | // Adds a location field to test results 143 | // testLocationInResults: false, 144 | 145 | // The glob patterns Jest uses to detect test files 146 | // testMatch: [ 147 | // "**/__tests__/**/*.[jt]s?(x)", 148 | // "**/?(*.)+(spec|test).[tj]s?(x)" 149 | // ], 150 | 151 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 152 | // testPathIgnorePatterns: [ 153 | // "\\\\node_modules\\\\" 154 | // ], 155 | 156 | // The regexp pattern or array of patterns that Jest uses to detect test files 157 | // testRegex: [], 158 | 159 | // This option allows the use of a custom results processor 160 | // testResultsProcessor: undefined, 161 | 162 | // This option allows use of a custom test runner 163 | // testRunner: "jasmine2", 164 | 165 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 166 | // testURL: "http://localhost", 167 | 168 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 169 | // timers: "real", 170 | 171 | // A map from regular expressions to paths to transformers 172 | // transform: undefined, 173 | 174 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 175 | // transformIgnorePatterns: [ 176 | // "\\\\node_modules\\\\" 177 | // ], 178 | 179 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 180 | // unmockedModulePathPatterns: undefined, 181 | 182 | // Indicates whether each individual test should be reported during the run 183 | // verbose: undefined, 184 | 185 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 186 | // watchPathIgnorePatterns: [], 187 | 188 | // Whether to use watchman for file crawling 189 | // watchman: true, 190 | }; 191 | -------------------------------------------------------------------------------- /tests/localeShort.spec.ts: -------------------------------------------------------------------------------- 1 | import * as yup from 'yup'; 2 | 3 | import { ptShort } from '../src'; 4 | 5 | yup.setLocale(ptShort); 6 | 7 | yup.addMethod(yup.mixed, 'alwaysInvalid', function method() { 8 | return this.test({ 9 | test: () => false, 10 | }); 11 | }); 12 | 13 | describe('locale', () => { 14 | it('should return localized messages for mixed group', async () => { 15 | const schema = yup.object().shape({ 16 | defaultField: yup.mixed().alwaysInvalid(), 17 | requiredField: yup.mixed().required(), 18 | oneOfField: yup.mixed().oneOf([1, 2, 3]), 19 | notOneOfField: yup.mixed().notOneOf([1, 2, 3]), 20 | notTypeFieldNullIntention: yup.date(), 21 | notTypeField: yup.date(), 22 | definedField: yup.mixed().defined(), 23 | }); 24 | 25 | const data = { 26 | defaultField: 'whatever', 27 | requiredField: null, 28 | oneOfField: 4, 29 | notOneOfField: 1, 30 | notTypeFieldNullIntention: null, 31 | notTypeField: 'not a date', 32 | definedField: undefined, 33 | }; 34 | 35 | try { 36 | await schema.validate(data, { abortEarly: false, strict: true }); 37 | } catch (err) { 38 | expect(err.errors.length).toEqual(7); 39 | expect(err.errors[0]).toStrictEqual('Inválido.'); 40 | expect(err.errors[1]).toStrictEqual('Obrigatório.'); 41 | expect(err.errors[2]).toStrictEqual('Deve ter um dos seguintes valores: 1, 2, 3.'); 42 | expect(err.errors[3]).toStrictEqual('Não deve ter nenhum dos seguintes valores: 1, 2, 3.'); 43 | expect(err.errors[4]).toStrictEqual('Deve ser do tipo `date`, mas o valor final é: `null`.\nSe a intenção era usar "null" como um valor em branco marque o esquema como `.nullable()`.'); 44 | expect(err.errors[5]).toStrictEqual('Deve ser do tipo `date`, mas o valor final é: `"not a date"`.'); 45 | expect(err.errors[6]).toStrictEqual('Não deve ser indefinido.'); 46 | } 47 | }); 48 | 49 | it('should return localized messages for mixed group (non-strict)', async () => { 50 | const schema = yup.object().shape({ 51 | notTypeFieldNullIntention: yup.date(), 52 | notTypeField: yup.date(), 53 | }); 54 | 55 | const data = { 56 | notTypeFieldNullIntention: null, 57 | notTypeField: 'not a date', 58 | }; 59 | 60 | try { 61 | await schema.validate(data, { abortEarly: false, strict: false }); 62 | } catch (err) { 63 | expect(err.errors.length).toEqual(2); 64 | expect(err.errors[0]).toStrictEqual('Deve ser do tipo `date`, mas o valor final é: `Invalid Date`.'); 65 | expect(err.errors[1]).toStrictEqual('Deve ser do tipo `date`, mas o valor final é: `Invalid Date` (cast do valor `"not a date"`).'); 66 | } 67 | }); 68 | 69 | it('should return localized messages for string group', async () => { 70 | const schema = yup.object().shape({ 71 | lengthFieldSingular: yup.string().length(1), 72 | minFieldSingular: yup.string().min(1), 73 | maxFieldSingular: yup.string().max(1), 74 | lengthFieldPlural: yup.string().length(5), 75 | minFieldPlural: yup.string().min(5), 76 | maxFieldPlural: yup.string().max(5), 77 | matchesField: yup.string().matches(/\d+/), 78 | emailField: yup.string().email(), 79 | urlField: yup.string().url(), 80 | trimField: yup.string().trim(), 81 | lowercaseField: yup.string().lowercase(), 82 | uppercaseField: yup.string().uppercase(), 83 | }); 84 | 85 | const data = { 86 | lengthFieldSingular: '', 87 | minFieldSingular: '', 88 | maxFieldSingular: '12', 89 | lengthFieldPlural: '1234', 90 | minFieldPlural: '1234', 91 | maxFieldPlural: '123456', 92 | matchesField: 'abc', 93 | emailField: 'not a e-mail', 94 | urlField: 'no a url', 95 | trimField: ' spaced sentence ', 96 | lowercaseField: 'NOT LOWER', 97 | uppercaseField: 'not upper', 98 | }; 99 | 100 | try { 101 | await schema.validate(data, { abortEarly: false, strict: true }); 102 | } catch (err) { 103 | expect(err.errors.length).toEqual(12); 104 | expect(err.errors[0]).toStrictEqual('Deve ter exatamente 1 caractere.'); 105 | expect(err.errors[1]).toStrictEqual('Deve ter pelo menos 1 caractere.'); 106 | expect(err.errors[2]).toStrictEqual('Deve ter no máximo 1 caractere.'); 107 | expect(err.errors[3]).toStrictEqual('Deve ter exatamente 5 caracteres.'); 108 | expect(err.errors[4]).toStrictEqual('Deve ter pelo menos 5 caracteres.'); 109 | expect(err.errors[5]).toStrictEqual('Deve ter no máximo 5 caracteres.'); 110 | expect(err.errors[6]).toStrictEqual('Deve corresponder ao padrão: "/\\d+/".'); 111 | expect(err.errors[7]).toStrictEqual('Deve ser um e-mail válido.'); 112 | expect(err.errors[8]).toStrictEqual('Deve ser uma URL válida.'); 113 | expect(err.errors[9]).toStrictEqual('Não deve conter espaços adicionais no início nem no fim.'); 114 | expect(err.errors[10]).toStrictEqual('Deve estar em letras minúsculas.'); 115 | expect(err.errors[11]).toStrictEqual('Deve estar em letras maiúsculas.'); 116 | } 117 | }); 118 | 119 | it('should return localized messages for number group', async () => { 120 | const schema = yup.object().shape({ 121 | minField: yup.number().min(10), 122 | maxField: yup.number().max(10), 123 | lessThanField: yup.number().lessThan(10), 124 | moreThanField: yup.number().moreThan(10), 125 | positiveField: yup.number().positive(), 126 | negativeField: yup.number().negative(), 127 | integerField: yup.number().integer(), 128 | }); 129 | 130 | const data = { 131 | minField: 9, 132 | maxField: 11, 133 | lessThanField: 11, 134 | moreThanField: 9, 135 | positiveField: -1, 136 | negativeField: 1, 137 | integerField: 0.5, 138 | }; 139 | 140 | try { 141 | await schema.validate(data, { abortEarly: false, strict: true }); 142 | } catch (err) { 143 | expect(err.errors.length).toEqual(7); 144 | expect(err.errors[0]).toStrictEqual('Deve ser maior ou igual a 10.'); 145 | expect(err.errors[1]).toStrictEqual('Deve ser menor ou igual a 10.'); 146 | expect(err.errors[2]).toStrictEqual('Deve ser menor que 10.'); 147 | expect(err.errors[3]).toStrictEqual('Deve ser maior que 10.'); 148 | expect(err.errors[4]).toStrictEqual('Deve ser um número positivo.'); 149 | expect(err.errors[5]).toStrictEqual('Deve ser um número negativo.'); 150 | expect(err.errors[6]).toStrictEqual('Deve ser um número inteiro.'); 151 | } 152 | }); 153 | 154 | it('should return localized messages for date group.', async () => { 155 | const schema = yup.object().shape({ 156 | minField: yup.date().min(new Date(2020, 1, 1)), 157 | maxField: yup.date().max(new Date(2020, 1, 1)), 158 | }); 159 | 160 | const data = { 161 | minField: new Date(2019, 12, 31), 162 | maxField: new Date(2020, 1, 2), 163 | }; 164 | 165 | try { 166 | await schema.validate(data, { abortEarly: false, strict: true }); 167 | } catch (err) { 168 | expect(err.errors.length).toEqual(2); 169 | expect(err.errors[0]).toStrictEqual('Deve ser posterior a 2020-02-01T03:00:00.000Z.'); 170 | expect(err.errors[1]).toStrictEqual('Deve ser anterior a 2020-02-01T03:00:00.000Z.'); 171 | } 172 | }); 173 | 174 | it('should return localized messages for object group', async () => { 175 | const schema = yup.object().shape({}).noUnknown(); 176 | 177 | const data = { 178 | unknownField: 'whatever', 179 | }; 180 | 181 | try { 182 | await schema.validate(data, { abortEarly: false, strict: true }); 183 | } catch (err) { 184 | expect(err.errors.length).toEqual(1); 185 | expect(err.errors[0]).toStrictEqual('Existem chaves desconhecidas: unknownField.'); 186 | } 187 | }); 188 | 189 | it('should return localized messages for array group', async () => { 190 | const schema = yup.object().shape({ 191 | minFieldSingular: yup.array().min(1), 192 | maxFieldSingular: yup.array().max(1), 193 | minFieldPlural: yup.array().min(5), 194 | maxFieldPlural: yup.array().max(5), 195 | }); 196 | 197 | const data = { 198 | minFieldSingular: [], 199 | maxFieldSingular: [1, 2], 200 | minFieldPlural: [1, 2, 3, 4], 201 | maxFieldPlural: [1, 2, 3, 4, 5, 6], 202 | }; 203 | 204 | try { 205 | await schema.validate(data, { abortEarly: false, strict: true }); 206 | } catch (err) { 207 | expect(err.errors.length).toEqual(4); 208 | expect(err.errors[0]).toStrictEqual('Deve ter pelo menos 1 item.'); 209 | expect(err.errors[1]).toStrictEqual('Deve ter no máximo 1 item.'); 210 | expect(err.errors[2]).toStrictEqual('Deve ter pelo menos 5 itens.'); 211 | expect(err.errors[3]).toStrictEqual('Deve ter no máximo 5 itens.'); 212 | } 213 | }); 214 | }); 215 | -------------------------------------------------------------------------------- /tests/localeForm.spec.ts: -------------------------------------------------------------------------------- 1 | import * as yup from 'yup'; 2 | 3 | import { ptForm } from '../src'; 4 | 5 | yup.setLocale(ptForm); 6 | 7 | yup.addMethod(yup.mixed, 'alwaysInvalid', function method() { 8 | return this.test({ 9 | test: () => false, 10 | }); 11 | }); 12 | 13 | describe('locale', () => { 14 | it('should return localized messages for mixed group', async () => { 15 | const schema = yup.object().shape({ 16 | defaultField: yup.mixed().alwaysInvalid(), 17 | requiredField: yup.mixed().required(), 18 | oneOfField: yup.mixed().oneOf([1, 2, 3]), 19 | notOneOfField: yup.mixed().notOneOf([1, 2, 3]), 20 | notTypeFieldNullIntention: yup.date(), 21 | notTypeField: yup.date(), 22 | definedField: yup.mixed().defined(), 23 | }); 24 | 25 | const data = { 26 | defaultField: 'whatever', 27 | requiredField: null, 28 | oneOfField: 4, 29 | notOneOfField: 1, 30 | notTypeFieldNullIntention: null, 31 | notTypeField: 'not a date', 32 | definedField: undefined, 33 | }; 34 | 35 | try { 36 | await schema.validate(data, { abortEarly: false, strict: true }); 37 | } catch (err) { 38 | expect(err.errors.length).toEqual(7); 39 | expect(err.errors[0]).toStrictEqual('O campo é inválido.'); 40 | expect(err.errors[1]).toStrictEqual('O campo é obrigatório.'); 41 | expect(err.errors[2]).toStrictEqual('O campo deve ter um dos seguintes valores: 1, 2, 3.'); 42 | expect(err.errors[3]).toStrictEqual('O campo não deve ter nenhum dos seguintes valores: 1, 2, 3.'); 43 | expect(err.errors[4]).toStrictEqual('O campo deve ser do tipo `date`, mas o valor final é: `null`.\nSe a intenção era usar "null" como um valor em branco marque o esquema como `.nullable()`.'); 44 | expect(err.errors[5]).toStrictEqual('O campo deve ser do tipo `date`, mas o valor final é: `"not a date"`.'); 45 | expect(err.errors[6]).toStrictEqual('O campo não deve ser indefinido.'); 46 | } 47 | }); 48 | 49 | it('should return localized messages for mixed group (non-strict)', async () => { 50 | const schema = yup.object().shape({ 51 | notTypeFieldNullIntention: yup.date(), 52 | notTypeField: yup.date(), 53 | }); 54 | 55 | const data = { 56 | notTypeFieldNullIntention: null, 57 | notTypeField: 'not a date', 58 | }; 59 | 60 | try { 61 | await schema.validate(data, { abortEarly: false, strict: false }); 62 | } catch (err) { 63 | expect(err.errors.length).toEqual(2); 64 | expect(err.errors[0]).toStrictEqual('O campo deve ser do tipo `date`, mas o valor final é: `Invalid Date`.'); 65 | expect(err.errors[1]).toStrictEqual('O campo deve ser do tipo `date`, mas o valor final é: `Invalid Date` (cast do valor `"not a date"`).'); 66 | } 67 | }); 68 | 69 | it('should return localized messages for string group', async () => { 70 | const schema = yup.object().shape({ 71 | lengthFieldSingular: yup.string().length(1), 72 | minFieldSingular: yup.string().min(1), 73 | maxFieldSingular: yup.string().max(1), 74 | lengthFieldPlural: yup.string().length(5), 75 | minFieldPlural: yup.string().min(5), 76 | maxFieldPlural: yup.string().max(5), 77 | matchesField: yup.string().matches(/\d+/), 78 | emailField: yup.string().email(), 79 | urlField: yup.string().url(), 80 | trimField: yup.string().trim(), 81 | lowercaseField: yup.string().lowercase(), 82 | uppercaseField: yup.string().uppercase(), 83 | }); 84 | 85 | const data = { 86 | lengthFieldSingular: '', 87 | minFieldSingular: '', 88 | maxFieldSingular: '12', 89 | lengthFieldPlural: '1234', 90 | minFieldPlural: '1234', 91 | maxFieldPlural: '123456', 92 | matchesField: 'abc', 93 | emailField: 'not a e-mail', 94 | urlField: 'no a url', 95 | trimField: ' spaced sentence ', 96 | lowercaseField: 'NOT LOWER', 97 | uppercaseField: 'not upper', 98 | }; 99 | 100 | try { 101 | await schema.validate(data, { abortEarly: false, strict: true }); 102 | } catch (err) { 103 | expect(err.errors.length).toEqual(12); 104 | expect(err.errors[0]).toStrictEqual('O campo deve ter exatamente 1 caractere.'); 105 | expect(err.errors[1]).toStrictEqual('O campo deve ter pelo menos 1 caractere.'); 106 | expect(err.errors[2]).toStrictEqual('O campo deve ter no máximo 1 caractere.'); 107 | expect(err.errors[3]).toStrictEqual('O campo deve ter exatamente 5 caracteres.'); 108 | expect(err.errors[4]).toStrictEqual('O campo deve ter pelo menos 5 caracteres.'); 109 | expect(err.errors[5]).toStrictEqual('O campo deve ter no máximo 5 caracteres.'); 110 | expect(err.errors[6]).toStrictEqual('O campo deve corresponder ao padrão: "/\\d+/".'); 111 | expect(err.errors[7]).toStrictEqual('O campo deve ser um e-mail válido.'); 112 | expect(err.errors[8]).toStrictEqual('O campo deve ser uma URL válida.'); 113 | expect(err.errors[9]).toStrictEqual('O campo não deve conter espaços adicionais no início nem no fim.'); 114 | expect(err.errors[10]).toStrictEqual('O campo deve estar em letras minúsculas.'); 115 | expect(err.errors[11]).toStrictEqual('O campo deve estar em letras maiúsculas.'); 116 | } 117 | }); 118 | 119 | it('should return localized messages for number group', async () => { 120 | const schema = yup.object().shape({ 121 | minField: yup.number().min(10), 122 | maxField: yup.number().max(10), 123 | lessThanField: yup.number().lessThan(10), 124 | moreThanField: yup.number().moreThan(10), 125 | positiveField: yup.number().positive(), 126 | negativeField: yup.number().negative(), 127 | integerField: yup.number().integer(), 128 | }); 129 | 130 | const data = { 131 | minField: 9, 132 | maxField: 11, 133 | lessThanField: 11, 134 | moreThanField: 9, 135 | positiveField: -1, 136 | negativeField: 1, 137 | integerField: 0.5, 138 | }; 139 | 140 | try { 141 | await schema.validate(data, { abortEarly: false, strict: true }); 142 | } catch (err) { 143 | expect(err.errors.length).toEqual(7); 144 | expect(err.errors[0]).toStrictEqual('O campo deve ser maior ou igual a 10.'); 145 | expect(err.errors[1]).toStrictEqual('O campo deve menor ou igual a 10.'); 146 | expect(err.errors[2]).toStrictEqual('O campo deve ser menor que 10.'); 147 | expect(err.errors[3]).toStrictEqual('O campo deve ser maior que 10.'); 148 | expect(err.errors[4]).toStrictEqual('O campo deve ser um número positivo.'); 149 | expect(err.errors[5]).toStrictEqual('O campo deve ser um número negativo.'); 150 | expect(err.errors[6]).toStrictEqual('O campo deve ser um número inteiro.'); 151 | } 152 | }); 153 | 154 | it('should return localized messages for date group.', async () => { 155 | const schema = yup.object().shape({ 156 | minField: yup.date().min(new Date(2020, 1, 1)), 157 | maxField: yup.date().max(new Date(2020, 1, 1)), 158 | }); 159 | 160 | const data = { 161 | minField: new Date(2019, 12, 31), 162 | maxField: new Date(2020, 1, 2), 163 | }; 164 | 165 | try { 166 | await schema.validate(data, { abortEarly: false, strict: true }); 167 | } catch (err) { 168 | expect(err.errors.length).toEqual(2); 169 | expect(err.errors[0]).toStrictEqual('O campo deve ser posterior a 2020-02-01T03:00:00.000Z.'); 170 | expect(err.errors[1]).toStrictEqual('O campo deve ser anterior a 2020-02-01T03:00:00.000Z.'); 171 | } 172 | }); 173 | 174 | it('should return localized messages for object group', async () => { 175 | const schema = yup.object().shape({}).noUnknown(); 176 | 177 | const data = { 178 | unknownField: 'whatever', 179 | }; 180 | 181 | try { 182 | await schema.validate(data, { abortEarly: false, strict: true }); 183 | } catch (err) { 184 | expect(err.errors.length).toEqual(1); 185 | expect(err.errors[0]).toStrictEqual('O campo tem chaves desconhecidas: unknownField.'); 186 | } 187 | }); 188 | 189 | it('should return localized messages for array group', async () => { 190 | const schema = yup.object().shape({ 191 | minFieldSingular: yup.array().min(1), 192 | maxFieldSingular: yup.array().max(1), 193 | minFieldPlural: yup.array().min(5), 194 | maxFieldPlural: yup.array().max(5), 195 | }); 196 | 197 | const data = { 198 | minFieldSingular: [], 199 | maxFieldSingular: [1, 2], 200 | minFieldPlural: [1, 2, 3, 4], 201 | maxFieldPlural: [1, 2, 3, 4, 5, 6], 202 | }; 203 | 204 | try { 205 | await schema.validate(data, { abortEarly: false, strict: true }); 206 | } catch (err) { 207 | expect(err.errors.length).toEqual(4); 208 | expect(err.errors[0]).toStrictEqual('O campo deve ter pelo menos 1 item.'); 209 | expect(err.errors[1]).toStrictEqual('O campo deve ter no máximo 1 item.'); 210 | expect(err.errors[2]).toStrictEqual('O campo deve ter pelo menos 5 itens.'); 211 | expect(err.errors[3]).toStrictEqual('O campo deve ter no máximo 5 itens.'); 212 | } 213 | }); 214 | }); 215 | -------------------------------------------------------------------------------- /tests/locale.spec.ts: -------------------------------------------------------------------------------- 1 | import * as yup from 'yup'; 2 | 3 | import { pt } from '../src'; 4 | 5 | yup.setLocale(pt); 6 | 7 | yup.addMethod(yup.mixed, 'alwaysInvalid', function method() { 8 | return this.test({ 9 | test: () => false, 10 | }); 11 | }); 12 | 13 | describe('locale', () => { 14 | it('should return localized messages for mixed group', async () => { 15 | const schema = yup.object().shape({ 16 | defaultField: yup.mixed().alwaysInvalid(), 17 | requiredField: yup.mixed().required(), 18 | oneOfField: yup.mixed().oneOf([1, 2, 3]), 19 | notOneOfField: yup.mixed().notOneOf([1, 2, 3]), 20 | notTypeFieldNullIntention: yup.date(), 21 | notTypeField: yup.date(), 22 | definedField: yup.mixed().defined(), 23 | }); 24 | 25 | const data = { 26 | defaultField: 'whatever', 27 | requiredField: null, 28 | oneOfField: 4, 29 | notOneOfField: 1, 30 | notTypeFieldNullIntention: null, 31 | notTypeField: 'not a date', 32 | definedField: undefined, 33 | }; 34 | 35 | try { 36 | await schema.validate(data, { abortEarly: false, strict: true }); 37 | } catch (err) { 38 | expect(err.errors.length).toEqual(7); 39 | expect(err.errors[0]).toStrictEqual('defaultField é inválido'); 40 | expect(err.errors[1]).toStrictEqual('requiredField é obrigatório'); 41 | expect(err.errors[2]).toStrictEqual('oneOfField deve ter um dos seguintes valores: 1, 2, 3'); 42 | expect(err.errors[3]).toStrictEqual('notOneOfField não deve ter nenhum dos seguintes valores: 1, 2, 3'); 43 | expect(err.errors[4]).toStrictEqual('notTypeFieldNullIntention deve ser do tipo `date`, mas o valor final é: `null`\nse a intenção era usar "null" como um valor em branco marque o esquema como `.nullable()`'); 44 | expect(err.errors[5]).toStrictEqual('notTypeField deve ser do tipo `date`, mas o valor final é: `"not a date"`'); 45 | expect(err.errors[6]).toStrictEqual('definedField não deve ser indefinido'); 46 | } 47 | }); 48 | 49 | it('should return localized messages for mixed group (non-strict)', async () => { 50 | const schema = yup.object().shape({ 51 | notTypeFieldNullIntention: yup.date(), 52 | notTypeField: yup.date(), 53 | }); 54 | 55 | const data = { 56 | notTypeFieldNullIntention: null, 57 | notTypeField: 'not a date', 58 | }; 59 | 60 | try { 61 | await schema.validate(data, { abortEarly: false, strict: false }); 62 | } catch (err) { 63 | expect(err.errors.length).toEqual(2); 64 | expect(err.errors[0]).toStrictEqual('notTypeFieldNullIntention deve ser do tipo `date`, mas o valor final é: `Invalid Date`'); 65 | expect(err.errors[1]).toStrictEqual('notTypeField deve ser do tipo `date`, mas o valor final é: `Invalid Date` (cast do valor `"not a date"`)'); 66 | } 67 | }); 68 | 69 | it('should return localized messages for string group', async () => { 70 | const schema = yup.object().shape({ 71 | lengthFieldSingular: yup.string().length(1), 72 | minFieldSingular: yup.string().min(1), 73 | maxFieldSingular: yup.string().max(1), 74 | lengthFieldPlural: yup.string().length(5), 75 | minFieldPlural: yup.string().min(5), 76 | maxFieldPlural: yup.string().max(5), 77 | matchesField: yup.string().matches(/\d+/), 78 | emailField: yup.string().email(), 79 | urlField: yup.string().url(), 80 | trimField: yup.string().trim(), 81 | lowercaseField: yup.string().lowercase(), 82 | uppercaseField: yup.string().uppercase(), 83 | }); 84 | 85 | const data = { 86 | lengthFieldSingular: '', 87 | minFieldSingular: '', 88 | maxFieldSingular: '12', 89 | lengthFieldPlural: '1234', 90 | minFieldPlural: '1234', 91 | maxFieldPlural: '123456', 92 | matchesField: 'abc', 93 | emailField: 'not a e-mail', 94 | urlField: 'no a url', 95 | trimField: ' spaced sentence ', 96 | lowercaseField: 'NOT LOWER', 97 | uppercaseField: 'not upper', 98 | }; 99 | 100 | try { 101 | await schema.validate(data, { abortEarly: false, strict: true }); 102 | } catch (err) { 103 | expect(err.errors.length).toEqual(12); 104 | expect(err.errors[0]).toStrictEqual('lengthFieldSingular deve ter exatamente 1 caractere'); 105 | expect(err.errors[1]).toStrictEqual('minFieldSingular deve ter pelo menos 1 caractere'); 106 | expect(err.errors[2]).toStrictEqual('maxFieldSingular deve ter no máximo 1 caractere'); 107 | expect(err.errors[3]).toStrictEqual('lengthFieldPlural deve ter exatamente 5 caracteres'); 108 | expect(err.errors[4]).toStrictEqual('minFieldPlural deve ter pelo menos 5 caracteres'); 109 | expect(err.errors[5]).toStrictEqual('maxFieldPlural deve ter no máximo 5 caracteres'); 110 | expect(err.errors[6]).toStrictEqual('matchesField deve corresponder ao padrão: "/\\d+/"'); 111 | expect(err.errors[7]).toStrictEqual('emailField deve ser um e-mail válido'); 112 | expect(err.errors[8]).toStrictEqual('urlField deve ser uma URL válida'); 113 | expect(err.errors[9]).toStrictEqual('trimField não deve conter espaços adicionais no início nem no fim'); 114 | expect(err.errors[10]).toStrictEqual('lowercaseField deve estar em letras minúsculas'); 115 | expect(err.errors[11]).toStrictEqual('uppercaseField deve estar em letras maiúsculas'); 116 | } 117 | }); 118 | 119 | it('should return localized messages for number group', async () => { 120 | const schema = yup.object().shape({ 121 | minField: yup.number().min(10), 122 | maxField: yup.number().max(10), 123 | lessThanField: yup.number().lessThan(10), 124 | moreThanField: yup.number().moreThan(10), 125 | positiveField: yup.number().positive(), 126 | negativeField: yup.number().negative(), 127 | integerField: yup.number().integer(), 128 | }); 129 | 130 | const data = { 131 | minField: 9, 132 | maxField: 11, 133 | lessThanField: 11, 134 | moreThanField: 9, 135 | positiveField: -1, 136 | negativeField: 1, 137 | integerField: 0.5, 138 | }; 139 | 140 | try { 141 | await schema.validate(data, { abortEarly: false, strict: true }); 142 | } catch (err) { 143 | expect(err.errors.length).toEqual(7); 144 | expect(err.errors[0]).toStrictEqual('minField deve ser maior ou igual a 10'); 145 | expect(err.errors[1]).toStrictEqual('maxField deve menor ou igual a 10'); 146 | expect(err.errors[2]).toStrictEqual('lessThanField deve ser menor que 10'); 147 | expect(err.errors[3]).toStrictEqual('moreThanField deve ser maior que 10'); 148 | expect(err.errors[4]).toStrictEqual('positiveField deve ser um número positivo'); 149 | expect(err.errors[5]).toStrictEqual('negativeField deve ser um número negativo'); 150 | expect(err.errors[6]).toStrictEqual('integerField deve ser um número inteiro'); 151 | } 152 | }); 153 | 154 | it('should return localized messages for date group', async () => { 155 | const schema = yup.object().shape({ 156 | minField: yup.date().min(new Date(2020, 1, 1)), 157 | maxField: yup.date().max(new Date(2020, 1, 1)), 158 | }); 159 | 160 | const data = { 161 | minField: new Date(2019, 12, 31), 162 | maxField: new Date(2020, 1, 2), 163 | }; 164 | 165 | try { 166 | await schema.validate(data, { abortEarly: false, strict: true }); 167 | } catch (err) { 168 | expect(err.errors.length).toEqual(2); 169 | expect(err.errors[0]).toStrictEqual('minField deve ser posterior a 2020-02-01T03:00:00.000Z'); 170 | expect(err.errors[1]).toStrictEqual('maxField deve ser anterior a 2020-02-01T03:00:00.000Z'); 171 | } 172 | }); 173 | 174 | it('should return localized messages for object group', async () => { 175 | const schema = yup.object().shape({}).noUnknown(); 176 | 177 | const data = { 178 | unknownField: 'whatever', 179 | }; 180 | 181 | try { 182 | await schema.validate(data, { abortEarly: false, strict: true }); 183 | } catch (err) { 184 | expect(err.errors.length).toEqual(1); 185 | expect(err.errors[0]).toStrictEqual('this tem chaves desconhecidas: unknownField'); 186 | } 187 | }); 188 | 189 | it('should return localized messages for array group', async () => { 190 | const schema = yup.object().shape({ 191 | minFieldSingular: yup.array().min(1), 192 | maxFieldSingular: yup.array().max(1), 193 | minFieldPlural: yup.array().min(5), 194 | maxFieldPlural: yup.array().max(5), 195 | }); 196 | 197 | const data = { 198 | minFieldSingular: [], 199 | maxFieldSingular: [1, 2], 200 | minFieldPlural: [1, 2, 3, 4], 201 | maxFieldPlural: [1, 2, 3, 4, 5, 6], 202 | }; 203 | 204 | try { 205 | await schema.validate(data, { abortEarly: false, strict: true }); 206 | } catch (err) { 207 | expect(err.errors.length).toEqual(4); 208 | expect(err.errors[0]).toStrictEqual('minFieldSingular deve ter pelo menos 1 item'); 209 | expect(err.errors[1]).toStrictEqual('maxFieldSingular deve ter no máximo 1 item'); 210 | expect(err.errors[2]).toStrictEqual('minFieldPlural deve ter pelo menos 5 itens'); 211 | expect(err.errors[3]).toStrictEqual('maxFieldPlural deve ter no máximo 5 itens'); 212 | } 213 | }); 214 | }); 215 | --------------------------------------------------------------------------------