gpt4 book ai didi

ruby-on-rails - Rails 指定验证顺序

转载 作者:行者123 更新时间:2023-12-03 16:07:58 25 4
gpt4 key购买 nike

我正在编写一个验证器类,它具有三个验证,在调用 MyVariableName.valid? 时运行。

validates_length_of :id_number, :is => 13, :message => "A SA ID has to be 13 digits long"
validates_format_of :id_number, :with => /^[0-9]+$/, :message => "A SA ID cannot have any symbols or letters"
validate :sa_id_validator

第三个是自定义验证器。问题是我的验证器 sa_id_validator要求传入的数据是13位数字,否则会报错。我如何确保 validate :sa_id_validator是只在前两个运行后才考虑?

抱歉,如果这是一个非常简单的问题,我昨天下午都在尝试解决这个问题。

注意:这个验证器必须运行超过几千个条目,并且还运行在电子表格上传上,所以我需要它快..

我看到了一种这样做的方法,但它可能会运行两次验证,这在我的情况下会很糟糕。

编辑:

我的自定义验证器看起来像这样
def sa_id_validator
#note this is specific to South African id's
id_makeup = /(\d{6})(\d{4})(\d{1})(\d{1})(\d{1})/.match(@id_number)
birthdate = /(\d{2})(\d{2})(\d{2})/.match(id_makeup[1])
citizenship = id_makeup[3]
variable = id_makeup[4]
validator_key = id_makeup[5]

birthdate_validator(birthdate) && citizenship_validator(citizenship) && variable_validator(variable) && id_algorithm(id_makeup[0], validator_key)
end

private

def birthdate_validator(birthdate)
Date.valid_date?(birthdate[1].to_i,birthdate[2].to_i,birthdate[3].to_i)
end

def citizenship_validator(citizenship)
/[0]|[1]/.match(citizenship)
end

def variable_validator(variable)
/[8]|[9]/.match(variable)
end

def id_algorithm(id_num, validator_key)
odd_numbers = digits_at_odd_positions
even_numbers = digits_at_even_positions
# step1: the sum off all the digits in odd positions excluding the last digit.
odd_numbers.pop
a = odd_numbers.inject {|sum, x| sum + x}
# step2: concate all the digits in the even positions.
b = even_numbers.join.to_i
# step3: multiply step2 by 2 then add all the numbers in the result together
b_multiplied = (b*2)
b_multiplied_array = b_multiplied.to_s.split('')
int_array = b_multiplied_array.collect{|i| i.to_i}
c = int_array.inject {|sum, x| sum + x}
# step4: add the result from step 1 and 3 together
d = a + c
# step5: the last digit of the id must equal the result of step 4 mod 10, subtracted from 10
return false unless
validator_key == 10 - (d % 10)
end

def digits_at_odd_positions
id_num_as_array.values_at(*id_num_as_array.each_index.select(&:even?))
end

def digits_at_even_positions
id_num_as_array.values_at(*id_num_as_array.each_index.select(&:odd?))
end

def id_num_as_array
id_number.split('').map(&:to_i)
end
end

如果我添加 :calculations_ok => true归因于我的验证,然后传入一个 12 位数字,而不是我收到此错误:
i.valid?
NoMethodError: undefined method `[]' for nil:NilClass
from /home/ruberto/work/toolkit_3/toolkit/lib/id_validator.rb:17:in `sa_id_validator'

所以你可以看到它进入自定义验证,即使它应该失败 validates_length_of :id_number ??

最佳答案

我不太确定,但我在一些博客上读到 Rails 总是运行所有验证,即使第一个验证无效。

您可以做的是使您的自定义方法变得灵活或有弹性,以便我可以处理所有情况。

answer肯定会帮助你。

希望它能回答你的问题

关于ruby-on-rails - Rails 指定验证顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15083319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com