Mike Will
Mike Will

Reputation: 11

Validation of a username with regex

Trying to solve a regex sign-on problem. Here are the rules:

Here are the test cases it must pass:

Test.describe("Basic tests") do
  Test.assert_equals(validate_usr('asddsa'), true)
  Test.assert_equals(validate_usr('a'), false)
  Test.assert_equals(validate_usr('Hass'), false)
  Test.assert_equals(validate_usr('Hasd_12assssssasasasasasaasasasasas'), false)
  Test.assert_equals(validate_usr(''), false)
  Test.assert_equals(validate_usr('____'), true)
  Test.assert_equals(validate_usr('012'), false)
  Test.assert_equals(validate_usr('p1pp1'), true)
  Test.assert_equals(validate_usr('asd43 34'), false)
  Test.assert_equals(validate_usr('asd43_34'), true)
end

This is my code:

def validate_usr(username)
  if (username.length > 3 && username == username.downcase)
    return true
  elsif
    username.include?(" ") == true
    return false 
  else 
    return false
  end
end

Running into issues with the test case 9 that has a space involved. It returns true.

Upvotes: 0

Views: 460

Answers (1)

cozyconemotel
cozyconemotel

Reputation: 1161

Test case 9 returns true because it satisfies username.length > 3 && username == username.downcase. Note that " ".downcase == " " here.

Move that return false if username.include?(" ") up and it should work. I honestly suggest using Regex though.

def validate_usr(username)
  /\A[a-z0-9_]{4,16}\z/ === username
end

Upvotes: 2

Related Questions