我有url模型有url列,我想验证该列是一个有效的URL,我试过这个:
class User < ActiveRecord::Base validates_format_of :url, :with => URI::regexp(%w(http https)) end
但是当我输入这个网址时:http://ruby3arabi
它接受它,任何想法?
我测试过并发现URI :: regexp(%w(http https))或URI :: regexp不够好.
故障排除是使用此正则表达式
/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
选项:
我不区分大小写
x - 忽略正则表达式中的空格
因此,如果要在模型中进行验证,则应使用此代码:
class User < ActiveRecord::Base URL_REGEXP = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix validates :url, format: { with: URL_REGEXP, message: 'You provided invalid URL' } end
测试:
[1] URI :: regexp(%w(http https))
使用错误的网址进行测试:
http:// ruby3arabi - 结果无效
http:// http://ruby3arabi.com - 结果无效
http:// - 结果无效
使用正确的网址进行测试:
http://ruby3arabi.com - 结果无效
http://www.ruby3arabi.com - 结果无效
https://www.ruby3arabi.com - 结果无效
https://www.ruby3arabi.com/article/1 - 结果无效
https://www.ruby3arabi.com/websites/58e212ff6d275e4bf9000000?locale=en - 结果无效
[2] URI :: regexp
使用错误的网址进行测试:
http:// ruby3arabi - 结果有效
http:// http://ruby3arabi.com - 结果有效
http:// - 结果有效
使用正确的网址进行测试:
http://ruby3arabi.com - 结果有效
http://www.ruby3arabi.com - 结果有效
https://www.ruby3arabi.com - 结果有效
https://www.ruby3arabi.com/article/1 - 结果有效
https://www.ruby3arabi.com/websites/58e212ff6d275e4bf9000000?locale=en - 结果有效
[3] /^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[az ] {2,5}(:[ 0-9] {1,5})?(/.)?$/ix
使用错误的网址进行测试:
http:// ruby3arabi - 结果无效
http:// http://ruby3arabi.com - 结果无效
http:// - 结果无效
使用正确的网址进行测试:
http://ruby3arabi.com - 结果有效
http://www.ruby3arabi.com - 结果有效
https://www.ruby3arabi.com - 结果有效
https://www.ruby3arabi.com/article/1 - 结果有效
https://www.ruby3arabi.com/websites/58e212ff6d275e4bf9000000?locale=en - 结果有效