Skip to content

Instantly share code, notes, and snippets.

@michelmany
Last active April 22, 2023 00:42
Show Gist options
  • Save michelmany/523412a313351e02e20a1d5afe507795 to your computer and use it in GitHub Desktop.
Save michelmany/523412a313351e02e20a1d5afe507795 to your computer and use it in GitHub Desktop.
Vue.js 2 Vee-validate (pt-br) CPF Validation
// 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)
})
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
@daasc
Copy link

daasc commented Jun 25, 2020

como fica no componente ?

@igordelorenzi
Copy link

@daasc, cheguei um pouco tarde, mas é assim (VeeValidate 3.x):

<ValidationProvider rules="required|cpf" v-slot="{ errors }">
  <input
    id="cardHolderCPF"
    type="text"
    name="cpf"
    v-model="cardHolderCPF"
    v-mask="'###.###.###-##'"
    placeholder="___.___.___-__"
    class="input focus:outline-none focus:shadow mb-2"
    :class="{'border-red-500 error': errors.length > 0}"
    autocomplete="cpf"
    required
  />
  <p class="text-red-500 text-xs italic" v-show="errors.length > 0">{{ errors[0] }}</p>
</ValidationProvider>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment