我正在学习Rails,并坚持使用此自定义验证。我尝试了很多不同的方法来通过名为(:cpf)
的表单字段来验证,但没有成功。我也尝试使用ActiveModel :: EachValidator,但我变得更加困惑。验证是一个使用模11的校验位。所以这就是我最终的结果。Rails 5自定义验证
控制器/ drivers_controller.rb
def new
@driver = Driver.new
end
def create
@driver = Driver.new(driver_params)
if @driver.save
flash[:success] = "Motorista cadastrado com sucesso!"
redirect_to @driver
else
render 'new'
end
end
型号/ driver.rb
class Driver < ApplicationRecord
validate :checkcpf
private
def checkcpf
return false if cpf.nil?
nulos = %w{12345678909 11111111111 22222222222 33333333333 44444444444 55555555555 66666666666 77777777777 88888888888 99999999999 00000000000}
valor = cpf.scan /[0-9]/
if valor.length == 11
unless nulos.member?(valor.join)
valor = valor.collect{|x| x.to_i}
soma = 10*valor[0]+9*valor[1]+8*valor[2]+7*valor[3]+6*valor[4]+5*valor[5]+4*valor[6]+3*valor[7]+2*valor[8]
soma = soma - (11 * (soma/11))
resultado1 = (soma == 0 or soma == 1) ? 0 : 11 - soma
if resultado1 == valor[9]
soma = valor[0]*11+valor[1]*10+valor[2]*9+valor[3]*8+valor[4]*7+valor[5]*6+valor[6]*5+valor[7]*4+valor[8]*3+valor[9]*2
soma = soma - (11 * (soma/11))
resultado2 = (soma == 0 or soma == 1) ? 0 : 11 - soma
return true if resultado2 == valor[10] # CPF VALIDO
end
end
end
return false # CPF INVALIDO
errors.add(:cpf, "CPF INVÁLIDO")
end
end
我觉得我缺少的是如何通过我的CPF现场验证。要么我收到错误消息或错过验证。
稍后,我将尝试使用ActiveModel :: EachValidator,以便从Rails中获得更好的理解。这就是我通常所做的,尝试按照我能理解的方式工作,然后重构Rails方式。
我感谢任何帮助!谢谢!
感谢您的帮助。也许我会创建一个模块来测试这个方法,并尝试验证它的真或假... –