Home > other >  rails validation with regex
rails validation with regex

Time:12-22

I'm reading agile web development with rails 6.

In chapter 7, Task B: validation and unite testing

class Product < ApplicationRecord
  validates :image_url, allow_blank: true, format: {
      with: %r{\.(gif|jpg|png)\z}i, 
  }

what does the i mean in the end here?

It should mean that it's ending with .git or .jpg or .png

CodePudding user response:

The i in your query tells the regex to match using a case insensitive match. There is nothing really unique to rails here so you may want to look into regexes in general to learn all the different terms you can use to modify your expression.

The expression %r{\.(gif|jpg|png)\z}i is equivalent to /\.(gif|jpg|png)\z/i

the \. means the period character the | is an or as you stated the \z is end of string with some caveats that you can read more about here: http://www.regular-expressions.info/anchors.html and the i is incentive case matching

This means you would match 'test.jpg', 'test.JPg', 'test.JPG' or any permutation of those three characters in any case preceded by a period that occurs at the end of the string.

Here are the docs for regex formats in ruby specific:

https://ruby-doc.org/2.7.7/Regexp.html

And here is something where you can play with and learn regexes in general and try some expressions yourself:

https://regexr.com

CodePudding user response:

short explain: The "i" at the end of the regular expression is a modifier that makes the expression case-insensitive. This means that it will match both upper and lowercase letters in the image URL.

  • Related