我的身份证明是8808135011086
。分解是:
880813
:出生日期格式为yy-mm-dd 5011
:性别(0001
- 4999
之间的任何内容均为女性且5000
- 9999
为男性)0
:是否是外国人86
:验证员编号,以确保其余部分合法将13位数字分成这样的组880813
,5011
,0
,86
很容易获得:
/\d{6}\d{4}\d{1}\d{2}/
如何让正则表达式查找\d{4}
数字,然后检查它是否在0001
- 9999
或5000
- 9999
之间?到目前为止我有一个代码如下:
private
def gender_validation(gender)
case gender
when :male
Employee.id_number.match(/\d{6}\d{4}\d{1}\d{2}/)
return true
when :famale
Employee.id_number.match(/\d{6}\d{4}\d{1}\d{2}/)
return true
else
return false
end
如果标记的性别为男性,那么它会找到第二部分5223
,如果它位于5000
和9999
之间,则会返回true。
我不只是在寻找答案;我也想知道如何做到这一点。
答案 0 :(得分:2)
雄性:
/\d{6}\[5-9]\d{3}\d{1}\d{2}/
女:
/\d{6}\[0-4]\d{3}\d{1}\d{2}/
答案 1 :(得分:1)
遵循Rails Guides: Active Record Validations and Callbacks
中推荐的自定义验证我建议的解决方案是:
class Employee < ActiveRecord::Base
validates_with EmployeeIdAndGenderValidator
attr_accessible :id_number, :gender
.
.
.
end
class EmployeeIdAndGenderValidator < ActiveModel::Validator
# my id is 8808135011086 This broken down
# {880813} is my birdthdate in the format yy-mm-dd
# {5011} means that i am male anything
# between 5000-9999 is male
# and 0001-4999 is female,
# the next number {0} is weather someone is foreign or not,
# the next two {86} is a validator number to make sure the rest is legit.
def validate(record)
id_number = record.id_number
unless id_number[/\d{13}/]
record.errors[:id_number] << "invalid id number"
else
brirth_date = id_number[(0..5)]
parsed_gender = id_number[(6..9)].to_i
foreign = id_number[10]
validator = id_number[(-2..-1)]
validate_gender(parsed_gender, record)
end
end
private
def validate_gender(parsed_gender, record)
if(parsed_gender < 1 || parsed_gender > 9999)
record.errors[:id_number] << "the id number had invalid gender number."
else
calculate_gender = (parsed_gender <= 4999 ? :female : :male)
unless record.gender == calculate_gender
record.errors[:gender] << "The extracted gender dont' match with the selected gender"
end
end
end
end
希望对你有所帮助!
P / S:对不起我的英语。