what does the instruction "name =~ /[A-Z].*/"? - ruby-on-rails

I'm studying ruby ​​on rails and I'm seeing a code, but I could not understand how it actually works.
''''ruby
validate: first_letter_must_be_uppercase
private
def first_letter_must_be_uppercase
errors.add ("name", "first letter must be uppercase") unless name =~ /[A-Z].*/
end

The code is basically checking that the string should contain the first letter in the upper case using the regular expression
explanation:
/[A-Z].*/
[A-Z] - Checks for any capital letter from A to Z
. - checks for any wildcard character
* - matches for 0 to any number of repetition.
To sum up
The input string should match the following format - A capital letter from A-Z and then should have 0 to any number of wildcard characters
You can check it on Rubular
EDIT
As pointed out by #vasfed if you want to match the first character the regex need to be changed to
/\A[A-Z].*/
\A - Ensure start of the string

Related

asp-net: data-annotation regex DOESN'T WORK

ASP-NET MVC PROJECT
I have tried to set a regular lookaround expression to a password field of a form. A simple example I tried is check that the user wrote a capital letter using System.ComponentModel.DataAnnotations.
Examples:
[RegularExpression("(?=.*[A-Z])", ErrorMessage = "You have to write
a capital letter")]
[RegularExpression(#"^(?=.*[A-Z])", ErrorMessage = "You have to
write a capital letter")]
I prove this regular expression in this web page:http://regexstorm.net/tester
and I think this patron is correct.
In the login view I am using the directive asp-validation-for=#Model.password for checking the model is correct and if is not the server print the error message in the view and this is what always happens.
MICROSOFT GUIDE:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference#lookarounds-at-a-glance
You must provide a pattern that consumes the entire string when using regex with RegularExpressionAttribute (see RegularExpression Validation attribute not working correctly). Your ^(?=.*[A-Z]) regex pattern matches only the start of a string position because ^ is an anchor asserting the string start position and the (?=.*[A-Z]) is a positive lookahead, a non-consuming pattern, that just returns "true" if there are zero or more chars other than line break chars as many as possible and then an ASCII uppercase letter.
You can use
[RegularExpression(#"^.*[A-Z].*", ErrorMessage = "You have to write a capital letter")]
Or, a more efficient
[RegularExpression(#"^[^A-Z]*[A-Z].*", ErrorMessage = "You have to write a capital letter")]
In case there can be line breaks in the input text, replace . with [\w\W]:
[RegularExpression(#"^[^A-Z]*[A-Z][\w\W]*", ErrorMessage = "You have to write a capital letter")]
Details:
^ - start of string
[^A-Z]* - zero or more chars other than ASCII uppercase letters
[A-Z] - an uppercase letter
[\w\W]* - zero or more chars as many as possible.

Regex for letters, numbers, dashes only?

I am trying to validate a second level domain (everything before the .com and after the https://) in Ruby so that I can pass it into my namecheap api requests. Here is what I have so far, but I am not familiar with regex
validates_format_of :sld, with: [a-zA-Z0-9-]
no spaces allowed
no special characters allowed
however, dashes are allowed
cannot start with a dash
cannot end with a dash
I know that uppercase characters do not work in domain names, but I don't want to make users enter their text again. I will downcase the user input and show a flash message on the next page.
How about
validates_format_of :sld, with: /\A[a-z\d][a-z\d-]*[a-z\d]\z/i
Explanation:
\A - match beginning of string
[a-z\d] - match any letter from a-z or number from 0-9 once
[a-z\d-] - match any letter from a-z, number from 0-9, or dash zero or more times
[a-z\d] - match any letter from a-z or number from 0-9 once
\z - match end of string
i flag - make matches case-insensitive
Note: this will only work for strings of length 2 or more. If you need to support single-character inputs,
I would just write a method that checks the string length and if it's a single character, ensure it's not a dash. If it's more than 2 characters, validate it with this regex.
This will probably work:
^[0-9A-Za-z](|[-0-9A-Za-z]{0,61}[0-9A-Za-z])$
Your string needs to start with a alphanumeric ([0-9A-Za-z])
Then, there are two choices ((|[-0-9A-Za-z]{0,61}[0-9A-Za-z])):
End of string
Between 0 and 61 alphanumeric or dash chars followed by an alphanumeric char. (For a maximum of 63 characters)
^ and $ are anchors
validates :sld, format: { with: /^(?!-)[-\w\d]{,63}(?<!-)$/i }
You can try out your regex at http://rubular.com/
^(?!-) - negative lookahead: cannot start with dash
[-\w\d] - match words \w, digits \d, or dash -
{,63} - match must be between 1 and 63 characters
(?<!-)$ - negative lookbehind: cannot end with dash
/i - case insensitive

Rails validate format with regex

In my rails app, I want to validate input on a string field containing any number of keywords (which could be more than 1 natural language word (e.g. "document number")). To recognize the individual keywords, I am entering them separated by ", " (or get their end by end of string).
For this I use
validates :keywords, presence: true, format: { with: /((\w+\s?-?\w+)(,|\z))/i, message: "please enter keywords in correct format"}
It should allow the attribute keywords (string) to contain: "word1, word2, word3 word4, word5-word6"
It should not allow the use of any other pattern. e.g. not "word1; word2;"
It does incorrectly allow "word1; word2"
On rubular, this regex works; yet in my rails app it allows for example "word1; word2" or "word3; word-"
where is my error (got to say am beginner in Ruby and regex)?
You need to use anchors \A and \z and modify the pattern to fit that logic as follows:
/\A(\w+(?:[\s-]*\w+)?)(?:,\s*\g<1>)*\z/
See the Rubular demo
Details:
\A - start of string
(\w+(?:[\s-]*\w+)?) - Group 1 capturing:
\w+ - 1 or more word chars
(?:[\s-]*\w+)? - 1 or 0 sequences of:
[\s-]* - 0+ whitespaces or -
\w+ - 1 or more word chars
(?:,\s*\g<1>)* - 0 or more sequences of:
,\s* - comma and 0+ whitespaces
\g<1> - the same pattern as in Group 1
\z - end of string.

Rails regex syntax error

I am trying to set a regex validation on a form with the code below. I want to allow any alphabetical character, including accents, numbers and hyphen, apostrophe, comma and space. This expression should match the result : "Tir à l'arc, 3d, danse"
validates :interest_list, tags: true, if: lambda { interest_list.any? }
validates :interest_list, format: { with: /\A[[:alpha:]\d-'’, ]\z/, message: "only allows letters, space, hyphen and apostrophe" }
But I have this error empty range in char class: /\A[[:alpha:]\d-'’,]\z/
Can anyone tell me what I'm doing wrong ?
Any - that appears inside a character class in any position other than the first or last is treated as a range, ie. [0-9] is shorthand for [0123456789]. This range is calculated based on the ASCII values.
You have \d-' in your regex and \d isn't valid to use for the start/end of a range. Probably what you want is to move - to the start or end of your []
/\A[[:alpha:]\d'’, -]\z/
...and to solve your next problem/question - as it is your regex will only match a single character, you probably also want a repeat on that character class, like a +:
/\A[[:alpha:]\d'’, -]+\z/
Error: Regex Construction ..
Invalid range end in character class
\A[[:alpha:]\d->>>HERE>>>'’, ]\z
\d - anything is invalid range because a range operator - cannot
specify a range between a class and anything else.
You'd need to escape the - to make it a literal \A[[:alpha:]\d\-'’, ]\z
or add it to the end or beginning \A[[:alpha:]\d'’, -]\z

How to update this REGEX to make sure string does not have _(underscore) at the end or beigning

This is the regular expression which i have, i need to make sure that string does not start or end with underscore , underscore may appear in between.
/^[a-zA-Z0-9_.-]+$/
I have tried
(?!_)
But doesn't seem to work
Allowed strings:
abcd
abcd_123
Not allowed strings:
abcd_
_abcd_123
Not too hard!
/^[^_].*[^_]$/
"Any character except an underscore at the start of the line (^[^_]), then any characters (.*), then any character except an underscore before the end of the line ([^_]$)."
This does require at least two characters to validate the string. If you want to allow one character lines:
/^[^_](.*[^_]|)$/
"Anything except an underscore to start the line, and then either some characters plus a non-underscore character before end-of-line, or just an immediate end-of-line.
You could approach this in the inverse way,
Check all those that do match starting and ending underscores like this:
/^_|_$/
^_ #starts with underscore
| #OR
_$ #ends with underscore
And then eliminate those that match. The above regexp is much more easier to read.
Check : http://www.rubular.com/r/H3Axvol13b
Or you can try the longer regex:
/^[a-zA-Z0-9.-][a-zA-Z0-9_.-]*[a-zA-Z0-9.-]$|^[a-zA-Z0-9.-]+$|^[a-zA-Z0-9.-][a-zA-Z0-9.-]$/
^[a-zA-Z0-9.-] #starts with a-z, or A-Z, or 0-9, or . -
[a-zA-Z0-9_.-]* #anything that can occur and the underscore
[a-zA-Z0-9.-]$ #ends with a-z, or A-Z, or 0-9, or . -
| #OR
^[a-zA-Z0-9.-]$ #for one-letter words
| #OR
^[a-zA-Z0-9.-][a-zA-Z0-9.-]$ #for two letter words
Check: http://www.rubular.com/r/FdtCqW6haG
/^[a-zA-Z0-9.-][a-zA-Z0-9_.-]+[a-zA-Z0-9.-]$/
Try this
Description:
In the first section, [a-zA-Z0-9.-], regex only allows lower and upper case alphabets, digits, dot and hyphen.
In the next section, [a-zA-Z0-9_.-]+, regex looks for a single or more than one characters that are lower or upper case alphabets, digits dot, hyphen or an underscore.
The last part, [a-zA-Z0-9.-], is the same as the first part that restricts the input to end with an underscore.
Try this:
Recently had the same concern and this is how I did it.
// '"^[a-zA-Z0-9_.-]*$"' → Alphanumeric and 「.」「_」「-」
// "^[^_].*[^_]$" → Reject start and end of string if contains 「_」
// (?=) REGEX AND operator
SLUG_REGEX = '"(?=^[a-zA-Z0-9_.-]*$)(?=^[^_].*[^_]$)"';
I used this snippet for my Laravel Validation so you may need to change the code as needed like " to / based on your code sample and other answers' code.

Resources