-1

我的身份证是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-99995000-之间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,如果它在 and 之间50009999它会返回 true。

我不只是在寻找答案;我也想知道如何做到这一点。

4

2 回答 2

2

男性:

/\d{6}\[5-9]\d{3}\d{1}\d{2}/

女性:

/\d{6}\[0-4]\d{3}\d{1}\d{2}/
于 2013-02-20T16:06:10.007 回答
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:对不起我的英语。

于 2013-02-20T17:54:00.727 回答