Ruby验证姓名,电子邮件和电话号码

时间:2016-06-01 03:01:52

标签: ruby

创建循环以检查电话号码是否为10个字符后,我相信电话问题现已解决。现在我正在检查电子邮件地址,名称并确保输出正确,并确保用户输入了2个名称。有问题让电子邮件地址以正确的格式验证和输出。

Set

2 个答案:

答案 0 :(得分:1)

我怀疑你不打算在这里使用赋值运算符:

if email =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

试试这个:

phone_number

您在if number = 10 方法中遇到类似错误:

if number.size == 10

我不确定你的意图。也许这个?

loop do
  if number.size == 10
    break   
  else
    puts "Invalid phone number entered. Please try again."
  end
end

然而,你有更多的问题。看一下这个循环:

number

如果号码无效,用户将如何退出此循环? $response = $gateway->purchase( [ 'amount' => '16.00', 'applicationFee' => '2.00', 'destination' => 'acct_24xxxxxxxxxxxxxx', 'currency' => 'AUD', 'card' => $formData, 'receipt_email' => 'xx@aaxxx.com', 'description' => 'Ref:10201', 'destination' => 'DESTINATION-ACCOUNT-ID', ] )->send(); 的值永远不会改变。

答案 1 :(得分:1)

这是一种Ruby风格的方法,可以解决您尝试做的事情:

# Define constants for things that are special and get re-used.
EMAIL_PATTERN = /\A\S+@\S+\z/

# Methods that test something and return true or false often end with
# a question mark (?) to indicate this.
def valid_email?(email)
  !!email.match(EMAIL_PATTERN)
end

# Try and keep your support methods separate from the main body of
# your program.

puts "Enter your email address (joe@info.com): "

# This sets up a loop that waits until you get a valid response.
while (email = gets)
  email = gets

  if valid_email?(email)
    puts "Great, that looks like it could work"
    break
  else
    # Note that the message is rendered here, not in the validation
    # method, so there's no assumptions about how this method is used.
    puts "Invalid email address entered. Please try again. "
  end
end

如果您尝试以这种方式构建代码,您会发现将事情组织起来要容易得多。这是学习编程时的一大挑战,以免不堪重负。

正则表达式非常适合验证符合特定模式的内容,但尽量不要对日常事物的模式过于自信。即使是简陋的IPv4地址也有多种形式。