Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Kirill Kovalchuk
Kirill Kovalchuk
2,533 Points

Confused with Rails 4 format validation [RESOLVED]

Hi. I'm confused with my tests failing on profile name validation (I'm going through Build A Simple Ruby on Rails application, but using Rails 4, not 3.2 as in the videos).

My problem is I've got this validator of profile_name:

  validates :profile_name,
            presence: true,
            uniqueness: true,
            format: {
              with: /\A[a-zA-Z0-9_\-]+\z/,
              message: "must be formatted correctly"
            }

And the following test fails:

  test "a user can have a correctly formatted profile name" do
    user = User.new(first_name: "Kirill",
                    last_name: "Kovalchuk",
                    email: "the.nemoden@gmail.com")
    user.password = user.password_confirmation = "qwerty1234"
    user.profile_name = "nemoden_1"
    assert user.valid?
  end

As the documatation says it's not safe to use ^ and $ since $ matches \n (new-line characted) which makes sense since I don't want people to have a possibility to enter an email like "john_doe@johndoeswebsite.com\n< script>/* guess who stole your cookies? */< /script >"

And the official documentation uses \A and \z in the examples here.

I don't wanna go with multiline option just to make test pass and then I'm using ^ and $ test don't pass either, it says:

<blockquote> The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option? (ArgumentError)</blockquote>

If I use IRB, it tests my profile name correctly:

$ irb
1.9.3p484 :002 > /\A[a-zA-Z0-9_\-]+\z/.match('nemoden_1')
 => #<MatchData "nemoden_1"> 

2 Answers

Kirill Kovalchuk
Kirill Kovalchuk
2,533 Points

Damn :) Sorry, Me as always:

The actual error was "has already been taken", I should've added debug before going to forum:

user.save
puts user.errors.inspect

is the actual code I needed, regex works correctly.

Michelle Cannito
Michelle Cannito
8,992 Points

I'm glad you had the "has already been taken" error because it caused you to post the correct regular expression-- the one that finally works.

Everyone, the "with" line should be as Kirill has it in his first post:

with: /\A[a-zA-Z0-9_\-]+\z/,

Thanks!