Regex for string first chars - Model validation

Hello everyone, in my Rails app I need to validate a string that on
creation
can not have its first chars empty or composed by any special chars.

For example: " file" and “%file” aren’t valid. Do you know what Regex I
should use?

Thanks!

On Fri, Feb 11, 2011 at 11:30 AM, Rodrigo Alves V.
[email protected]wrote:

Hello everyone, in my Rails app I need to validate a string that on
creation can not have its first chars empty or composed by any special
chars.

For example: " file" and “%file” aren’t valid. Do you know what Regex I
should use?

You could utilize the “anchor” for this – that is you say that the line
must “begin” with the characters that match the following regex.
Something like: /\A[\w]+$/ would work.

On Fri, Feb 11, 2011 at 11:30 AM, Rodrigo Alves V. [email protected]
wrote:
Hello everyone, in my Rails app I need to validate a string that on creation can
not have its first chars empty or composed by any special chars.

For example: " file" and “%file” aren’t valid. Do you know what Regex I should
use?

You could utilize the “anchor” for this – that is you say that the line must
“begin” with the characters that match the following regex.
Something like: /\A[\w]+$/ would work.

Note that \w will match an underscore. Don’t know if you consider that
“special” or not…

Hello, thanks for the reply, but after applying this regex I go to rails
console and run

a = File.new
a.file_name = " example.txt"

It still works, when it shouldn’t… any more help?

Undescore is allowed.

Underscore is allowed.

Philip’s idea seems pretty good:
^\w+
That says: look for any string that starts with one or more “word”
characters (letters, numbers, underscores).
Try it out in rubular:
http://rubular.com/
It let’s you quickly experiment with lots of regular expressions and
has a quick-ref right there on the page.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs