Note that there are some explanatory texts on larger screens.

plurals
  1. PORegex to validate user names with at least one letter and no special characters
    primarykey
    data
    text
    <p>I'm trying to write a user name validation that has the following restrictions:</p> <ol> <li>Must contain at least 1 letter (a-zA-Z)</li> <li>May not contain anything other than digits, letters, or underscores</li> </ol> <p>The following examples are valid: abc123, my_name, 12345a</p> <p>The following examples are invalid: 123456, my_name!, _1235</p> <p>I found something about using positive lookaheads for the letter contraint: (?=.*[a-zA-Z]), and it looks like there could be some sort of negative lookahead for the second constraint, but I'm not sure how to mix them together into one regex. (Note... I am not really clear on what the .* portion does inside the lookahead...)</p> <p>Is it something like this: /(?=.*[a-zA-Z])(?!.*[^a-zA-Z0-9_])/</p> <p><strong>Edit:</strong></p> <p>Because the question asks for a regex, the answer I'm accepting is:</p> <pre><code> /^[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$/ </code></pre> <p>However, the thing I'm actually going to implement is the suggestion by Bryan Oakley to split it into multiple smaller checks. This makes it easier to both read and extend in the future in case requirements change. Thanks all!</p> <p>And because I tagged this with ruby-on-rails, I'll include the code I'm actually using:</p> <pre><code>validate :username_format def username_format has_one_letter = username =~ /[a-zA-Z]/ all_valid_characters = username =~ /^[a-zA-Z0-9_]+$/ errors.add(:username, "must have at least one letter and contain only letters, digits, or underscores") unless (has_one_letter and all_valid_characters) end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload