Rails custom validation based on a regex?

前端 未结 3 2036
既然无缘
既然无缘 2020-12-16 19:20

I have the following regex that I use in my routes.rb for /type-in-something-here

# A-Z, a-z, 0-9, _ in the middle but never starting or ending in a _
# At l         


        
相关标签:
3条回答
  • 2020-12-16 19:48

    using something like this

    validates :uuid, :format => {:with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i},
                     :message => "your message"
    

    For more check this

    0 讨论(0)
  • 2020-12-16 19:57
    validates :name, format: { with: /\A[a-zA-Z]+\z/,
    message: "Only letters are allowed" }
    
    0 讨论(0)
  • 2020-12-16 19:59

    For validation purposes, remember to add the beginning and end of string markers \A and \Z:

    validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i
    

    Otherwise your regex will happily match any string that contains at least a letter or a digit. For some reason Rails implicitly adds the boundaries in the routes. (Probably because it embeds the regex inside a larger one to match the entire URL, with explicit checks for / and the end of the URL.)

    0 讨论(0)
提交回复
热议问题