Rails Validation Outside the Model
I need to make a validation for my message form, where the person enters an email and the email directs the form to the id of the person that will receive the message.
Email:<br />
<%= f.text_field :to %>
<%= error_message_on @message, :to %>
...
<%= submit_tag "Send" %>
My problem is that I need to create a validation for this form in order to accept just emails, but the Message model does not have an email itself. What would be the best try?
The create is like that
def create
@message = Message.new(params[:message])
@message.sender = @profile
@message.recipient = Profile.find_by_email(params[:message][:to])
if @message.save
flash[:notice] = "Message sent"
redirect_to profile_messages_path(@profile)
else
render :action => :new
end
end
Thanks in advance!
----EDIT----
As I said in a comment above, I added to message.rb the line
validates :to, :format => { :with => email_regex, :message => "Email possui formato incorreto" }
But doing some tests I found out that I cannot open my messages anymore, I get an error saying:
Validation开发者_开发百科 failed: To Email possui formato incorreto
Any clue?
This line
@message = Message.new(params[:message])
should throw an error if there is no to= method on the Message model. So I assume, you already have this kind of 'virtual attribute', so let's say something like this:
def to
@to
end
def to=(value)
@to = value
end
to validate for correct email addresses you could add this to the model:
validate :validate_email
def validate_email
errors.add :to, :invalid unless to.match /some email validation regex/
end
I hope this helps.
So if i understand correctly, you get an email that you just do not want to store in your model, because there is no such field.
A way to do it is use form_tag instead of form_for in order to create a custom form. Then, you can have as many non model attributes you want.
To check whether that is a correct mail, you would receive the params in your create action and have a method that check whether this is a valid email. If not, it would flash an error message and redirect to a page, if you would want that.
you can do a client side check via javascript, or you could do custom validations: http://www.perfectline.ee/blog/building-ruby-on-rails-3-custom-validators (are you using rails 3?)
精彩评论