我使用 Ruby 3.0.2 并試圖使用 ActiveRecord 進行驗證。
我希望驗證用戶輸入的字串,但希望將輸入的部分視為數字,以便我可以對其應用一些邏輯。
該輸入需要看起來像這樣
21-10
我將使用 regex 來確保這兩個數字之間有一個'-',但我希望能夠驗證這些數字,以確保:
- 兩組數字中的一組
- 兩組數字中的一組是21 兩個數字都不能大于21,除非它們之間的差值相差2。
我面臨的挑戰是如何將字串的部分內容作為數字進行驗證。
一個有效/無效輸入的例子:
11-21 // valid
10-23 // invalid because 23 > 21
11-11 // 無效,因為兩個數字都不是21
22-24 // valid because 22 & 24 within 2 of each other
感謝任何幫助!
uj5u.com熱心網友回復:
這可以用自定義驗證方法來完成,比如:
# in the model.
驗證:range_string_has_validate_pattern。
私有
def range_string_has validate_pattern
parts = range_string.split('-') # assuming the attribute is named `range_string`if parts.size != 2
errors.add(:range_string, "不包含由'-'分隔的兩個零件")
return[/span]。
結束。
begin
parts[0] = Integer(parts[0] )
parts[1] = Integer(parts[1] )
rescue[/span
errors.add(:range_string, "不包含兩個數字")
回傳。
結束。
return if parts[0] == 21 || parts[1] == 21
return if (parts[0] - parts[1]).abs == 2
errors.add(:range_string, "不符合要求"/span>)
結束。
uj5u.com熱心網友回復:
我會使用模式匹配(現代Ruby萬歲)和一個自定義驗證器方法
validates :your_attribute, format:/span> { with:/span> /Ad -d z/ }
驗證 :string_format 的有效性。
def string_format
# do not attempt if the format is wrong[/span]。
return if errors.where(:your_attribute).present?
case your_attribute.split('-'/span>).map(&:to_i)
in [.20, .20]
error.add(:your_attribute, ' Both numbers are less than 21')
in [...20, 22... ] | [22..., .20]
error.add(:your_attribute, 'One is less the other is more')
in [22... => x, 22... => y] if y - x > 2 or x - y > 2
error.add(:your_attribute, 'Difference is too big')
else[/span
return[/span]。
end
end end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/322756.html
標籤:
