My guess is, you’re wanting to check the total length of what they
entered… As the length of their username must be (for example)
between 5 and 20 characters long?
If so, I’d say you’re making things needlessly complex.
min = 5
max = 20
…
user_name = params[:user_name]
return false unless(
(min…max).include?(user_name.length) # check size
and user_name =~ /^\w/ # must start
with word-character
and user_name =~ /\w$/ # must end
with word-character
and user_name !~ /\W\W/) # no two
non-word-characters together
I know I could do it withs several lines of ruby, but I’d really like to
have it contained all within a single regex, as I am using it with
validates_format_of :with => /…/ in rails.
Pretty sure you can repeat “validates_format_of” as much as you like.
Regular expressions should always be broken up into simpler, easy to
understand, chunks. Especially when you’re validating user names and
the like.
If you do smash it all together, you write tests for all of your edge
cases and point that at a constant, containing your regex, at the top of
your model. To strengthen your regex muscles:
I’ve actually been using rubular - but unfortunately it isn’t quite as
helpful for more advanced regexes involving lookaheads / behinds etc.
Although I found a proper regex that worked using Joel’s example, a
better solution to the problem was just to use my existing regex with
validates_format_of, in conjunction with validates_size_of
I’ve actually been using rubular - but unfortunately it isn’t quite as
helpful for more advanced regexes involving lookaheads / behinds etc.
Although I found a proper regex that worked using Joel’s example, a
better solution to the problem was just to use my existing regex with
validates_format_of, in conjunction with validates_size_of
It’s worth noting that \w and \W do not handle utf-8 properly in all
cases, even with the u option. If you plan to allow/support i18n’ed
usernames, consider using Unicode character properties in you regular
expressions. For more information take a look at: