Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

ruby - Rails custom validation based on a regex?

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 least 5, no more than 500 characters

In the routes this works well as:

match ':uuid' => 'room#show', :constraints => { :uuid => /[A-Za-zd]([-w]{,498}[A-Za-zd])?/ }

I want to have this also as a validation so invalid records aren't created. So I added the following to room.rb:

validates_format_of :uuid, :with => /[A-Za-zd]([-w]{,498}[A-Za-zd])?/i, :message => "Invalid! Alphanumerics only."

But this validates_format_of isn't working, and instead of adding an error it's allow the record to save.

Any ideas what's wrong?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

validates_format_of :uuid, :with => /A[A-Za-zd]([-w]{,498}[A-Za-zd])?/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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...