1

I am trying to check that 3 condiditons are met when asking a user for an email. The user must input something, they must include the @ symbol, and include a domain (.com, .edu, .net, etc). For the domian I am mainly checking for a period. how do i make sure the user input meets these 3 conditions?

Here is the code I use:

    def email()
        print "What is the students email? "
        email = gets.chomp

        if email.empty? && email.include?("@") && email.include?(".")
            puts "working"
        else
            puts "Please enter a valid email. "
            email()
        end 
    end

    email()

Here is an example of me running the method in terminal:

Terminal output

I am using Ruby and VScode.

  • 3
    According to your code, email must be empty _and_ contain an @ and a dot. This cannot happen. – steenslag Oct 11 '22 at 21:25
  • Does this answer your question? [Ruby Email validation with regex](https://stackoverflow.com/questions/22993545/ruby-email-validation-with-regex) – nPn Oct 11 '22 at 22:33
  • Another way: `(i = str.index('@')) && str.index('.', i+2)`. See [String#index](https://ruby-doc.org/core-2.7.0/String.html#method-i-index). – Cary Swoveland Oct 12 '22 at 05:36
  • A small modification of your code here: " if ((!email.empty? && email.include?("@")) && (email.include?("."))) " this is not much useful as regex, but definitely a easy way for the new users in ruby – ajay_speed Oct 12 '22 at 06:03
  • 1
    See [here](https://rubygarage.org/blog/how-to-validate-emails) for a regex for domain names. – user1934428 Oct 12 '22 at 06:46
  • _"The user must input something"_ – in this case `email.empty?` should probably be `!email.empty?`, i.e. be _not_ empty. However, that emptiness check is superfluous because `include?('@')` / `include?('.')` can only become `true` if the email isn't empty. – Stefan Oct 12 '22 at 06:47

1 Answers1

2

You can use simple regexp like this

email.match?(/\A.+@.+\..+\z/)
/
  \A  # string begin
  .+  # minimum 1 character
  @   # @
  .+  # minimum 1 character
  \.  # dot
  .+  # minimum 1 character
  \z  # string end
/x
mechnicov
  • 12,025
  • 4
  • 33
  • 56