JNL
JNL

Reputation: 11

validating presence of email address (can't be blank)- Ruby on Rails

Pretty new at all this. I have a simple form for users to enter a couple pieces of information and then input their email address and push the submit button. I want to make it mandatory that they have to fill out their email address in order to push the submit button. If they don't fill out their email address they should get an error message on the email box that says the email can't be blank. I know this is super simple but I need exact help on where to put what code. I've been researching this all night and know that part of the code should go in the application_controller and other should go in the html file where the actual text_field:email is. I'd be grateful if someone could clearly tell me what the necessary steps are for doing this. Thanks!

Upvotes: 1

Views: 1419

Answers (3)

Schroedinger
Schroedinger

Reputation: 1283

From snipplr, place in your model

validates_format_of     :email,
                        :with       => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                        :message    => 'email must be valid'

Upvotes: 0

nuclearsandwich
nuclearsandwich

Reputation: 455

In Rails 2, which I would assume you are using, validations go in the model. Which is located in $Rails_app_directory/app/model/$Classname.rb

In order to add ActiveRecord validations you can use the line

validates_presence_of :email_address

You should also consider using Rails to generate a confirmation field and filtering out ill-formatted email addresses. You could accomplish the former with:

validates_confirmation_of :email_address

with this, all you need to add to your form is a text_field for :email_address_confirmation

and the latter with a regular expression such as:

validates_format_of :email_address, :with => /\A[\w\.%\+\-]+@(?:[A-Z0-9\-]+\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)\z/i

Upvotes: 3

Shripad Krishna
Shripad Krishna

Reputation: 10498

It should go in your model. Add this:

class Model < ActiveRecord::Base 
 validates_presence_of :email
end 

Check this link for more info: http://guides.rails.info/activerecord_validations_callbacks.html#validates-presence-of

Upvotes: 3

Related Questions