Skip to content

Instantly share code, notes, and snippets.

@IgorDePaula
Last active November 3, 2021 13:40
Show Gist options
  • Save IgorDePaula/b29338a84be89dbc0c3b1f30239bc83c to your computer and use it in GitHub Desktop.
Save IgorDePaula/b29338a84be89dbc0c3b1f30239bc83c to your computer and use it in GitHub Desktop.
vee-validate em pt-br
function calcChecker1 (firstNineDigits) {
let sum = null
for (let j = 0; j < 9; ++j) {
sum += firstNineDigits.toString().charAt(j) * (10 - j)
}
const lastSumChecker1 = sum % 11
const checker1 = (lastSumChecker1 < 2) ? 0 : 11 - lastSumChecker1
return checker1
}
function calcChecker2 (cpfWithChecker1) {
let sum = null
for (let k = 0; k < 10; ++k) {
sum += cpfWithChecker1.toString().charAt(k) * (11 - k)
}
const lastSumChecker2 = sum % 11
const checker2 = (lastSumChecker2 < 2) ? 0 : 11 - lastSumChecker2
return checker2
}
function cleaner (value) {
const digits = value.replace(/[^\d]/g, '')
return digits
}
function validate (value) {
const cleanCPF = cleaner(value)
const firstNineDigits = cleanCPF.substring(0, 9)
const checker = cleanCPF.substring(9, 11)
let result = false
for (let i = 0; i < 10; i++) {
if (firstNineDigits + checker === Array(12).join(i)) {
return false
}
}
const checker1 = calcChecker1(firstNineDigits)
const checker2 = calcChecker2(`${firstNineDigits}${checker1}`)
if (checker.toString() === checker1.toString() + checker2.toString()) {
result = true
} else {
result = false
}
return result
}
export default validate
import CpfValidate from './rules/cpf'
const validator = {
getMessage (field, args) { // will be added to default English messages.
return 'Invalid CPF'
},
validate (value, args) {
return CpfValidate(value)
}
}
export default validator
const dictionary = {
pt: {
messages: {
cpf: () => 'CPF inválido',
required: (field) => `O campo ${field} é obrigatório.`
}
}
}
export default dictionary
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VeeValidator, { Validator } from 'vee-validate'
import CpfValidator from './components/validators/cpf.validator'
import Dictionary from './components/validators/dictionary'
import Produto from './components/produtos.vue'
Validator.extend('cpf', CpfValidator)
Vue.use(VeeValidator, {locale: 'pt', dictionary: Dictionary})
Vue.config.debug = true
/* eslint-disable no-new */
Vue.component('produtos', Produto)
new Vue({
el: '#app',
render: h => h(App)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment