简体   繁体   中英

Custom validation message in Rails 4

I'm well aware that there are questions that ask this but I am not allowed to comment on any of them and in any case my question is a little different from those. I am trying to get a custom error message from a validation, where the custom error message does not have to begin with the attribute being validated.

My attribute is called "form_person" and represents the name of the person filling in a form (a legal requirement for the site I'm working on). So I have

validates_presence_of :form_person, message: "^We need to know who is filling in this form (your name)"

This used to work, as in the "^" would cause the message to be added to errors[:base] , but now it's not, and I get "Form person ^We need to know who is filling in this form (your name)", which is... well... less than helpful. I've seen a solution from like 2 years ago that involves messing around with the localization files, but that is honestly the last place in the entire world that I or any of the rest of our staff might look for a validation message, seeing as we're not localized at all. I know I can just write a custom validator method and that's probably what I'm going to have to do, but I don't like to do that because it's messy and needlessly pollutes the model namespace with extraneous methods. There's already the validates_presence_of method! I've looked all over the rails guides including the edge one and there's no mention of any way of doing this except via custom validator or (ugh) a custom validation class separate. Just checking for the presence of an attribute hardly seems like an appropriate thing to write a whole separate validator class for, so how can I do this conveniently in one succinct line like I used to be able to?

尝试这个:

validates :form_person, :presence => {message: "^We need to know who is filling in this form (your name)"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM