Skip to content

Instantly share code, notes, and snippets.

@alexrohleder
Created April 8, 2016 01:28
Show Gist options
  • Save alexrohleder/4e18de5a793f2ca79c20a803bcf510d9 to your computer and use it in GitHub Desktop.
Save alexrohleder/4e18de5a793f2ca79c20a803bcf510d9 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="app">
<p>Insira um cpf:</p>
<input type="text" v-model="message">
<button v-on:click="validate()">go</button>
<p v-if="validator.valid">Valido</p>
<p v-if="validator.valid == false">Invalido</p>
</div>
<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript">
let validator = {
data: {
validator: {
valid: null
}
},
methods: {
validate() {
this.validator.valid = true
for (let i in this.validations) {
this.validator[i] = {}
for (let k in this.validations[i]) {
let rule = k.charAt(0).toUpperCase() + k.slice(1)
this.validator[i][k] = this[`validate${rule}Field`](this[i], this.validations[i][k])
this.validator.valid = this.validator[i][k] ? this.validator.valid : false
}
}
},
validateMinlengthField(value, options) {
return value.length >= options
},
validateMaxlengthField(value, options) {
return value.length <= options
},
validateRequiredField(value, options) {
if (options == true) {
return value ? true : false
} else return true
},
validateNumericField(value, options) {
switch (options) {
case 'all_numbers': return /^[-+]?[0-9]+$/.test(value); break;
case 'positive_numbers': return /^[0-9]+$/.test(value); break;
}
},
validateCepField(value, options) {
return /([0-9]){5}\-([0-9]){3}/.test(value)
},
validateEmailField(value, options) {
return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/.text(value)
},
validateCpfField(value, options) {
let calcDigitosPos = (digitos, posicoes = 10, soma = 0) => {
for (let i = 0; i < digitos.length; ++i) {
soma = soma + (digitos[i] * posicoes)
--posicoes;
if (posicoes < 2) {
posicoes = 9
}
}
soma = soma % 11
if (soma < 2) {
soma = 0
} else soma = 11 - soma
return digitos + soma
}
let cpf = value.toString().replace(/[^0-9]/g, '')
return cpf === calcDigitosPos(calcDigitosPos(cpf.substr(0, 9)), 11)
}
}
}
new Vue({
el: '#app',
mixins: [validator],
data: {
message: 'hello world!',
validations: {
message: {
required: true,
cpf: true
}
}
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment