Valitation CPF e CNPJ Grails 3
17/09/2015 22:57
def validateCpf = { cpf ->
try{
boolean validado = true
int d1, d2
int dg1, dg2, resto
int dgcpf
d1 = d2 = 0
dg1 = dg2 = resto = 0
for (int i = 1; i < cpf.length() -1; i++) {
dgcpf = cpf.substring(i -1, i) as Integer
d1 = d1 + ( 11 - i ) * dgcpf
d2 = d2 + ( 12 - i ) * dgcpf
}
resto = (d1 % 11)
dg1 = (resto < 2) ? 0 : 11 - resto
d2 += 2 * dg1
resto = (d2 % 11)
dg2 = (resto < 2) ? 0 : 11 - resto
def dgverif = cpf.substring(cpf.length()-2)
def dgresult = (dg1 as String) + (dg2 as String)
return dgverif == dgresult
}catch (Exception e){
return false
}
}?
static constraints = {
?cpf validation: validateCpf
}?
grails clean?
grails package-plugin
grails install
dependencies {
runtime 'org.grails.plugins:BrValidation:0.3'
}
Class SuaClass{
?String cpf
?static constraints = {
?cpf (validator:{value, thiz, errors -> return thiz.seuService.validateCpf(value, thiz, errors)})
?}
}
? ?errors.rejectValue( "cpf", "sua_chave_para_mensagem_erro_i18n")se der tudo certo basta vc retornar "true"
return false
Para se registrar, clique aqui.