Rails:验证字符串的最小和最大长度,但将其留空 [英] Rails: Validating min and max length of a string but allowing it to be blank

查看:59
本文介绍了Rails:验证字符串的最小和最大长度,但将其留空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要验证的字段.我希望该字段可以保留为空白,但是如果用户正在输入数据,我希望它采用某种格式.当前,我在模型中使用以下验证,但这不允许用户将其留空:

validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5

我该如何写这篇文章来实现自己的目标?

解决方案

我认为可能需要这样的东西:

validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true

更多示例: ActiveRecord :: Validations :: ClassMethods

I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5

How do I write this to accomplish my goal?

解决方案

I think it might need something like:

validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true

More examples: ActiveRecord::Validations::ClassMethods

这篇关于Rails:验证字符串的最小和最大长度,但将其留空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆