validating presence of email address (can't be blank)- Ruby on Rails - 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!

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

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

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

Related

Trying to add validation to rails devise sign-up page

Kinda a noob rails programmer, but this would save me a ton of headache. Currently, I'm trying to add validation to my devise sign on page, such as only allowing the sign up to complete if their email ends with a certain extension. Does anyone know where the file location stands that overlooks the sign on page? I've looked over all models and views but can't seem to find it. Thank you!
I think that you can use validates_format_of in your user.rb model. You can use rubular.com to create the regex.
validates_format_of :email, :with => /MYREGEXHERE/
Simply add validation to your email field. There is nothing special you have to do. like:
validates :email, format: { with: /my_ending_string\z/, message: "must ends with my_ending_string" }

Custom Validation for format

I have a class Links. The class has these attributes
Twitter
Facebook
Pinterest
Quora
I want to write a validation that makes sure when a user inserts a link into a textbox it starts with http or https.
The validation works, but I have a an issue when the user does not insert a link at all. It still tries to run the validation on the empty attribute and raises the error. The below code is my attempt at checking for a empty attribute.
Here's my validation:
class Links < ActiveRecord::Base
attr_accessible :facebook, :twitter, :quora, :pinterest
validate :formatted_link
def formatted_link
links = %w(facebook twitter pinterest quora)
if links.any? {|link| self[link].nil?}
#Don't want it to do any validation if column is nil.
#Would like to drop column if user doesn't add a link.
else
validates_format_of links, :with => URI::regexp(%w(http https))
errors.add(:base, "Your link must start with http or https.")
end
end
Reason:
If a user just submits "www.twitter.com/username" the url get's appended to my sites url "mydomain.com/page/www.twitter.com/username. Not sure why this is happening. If there is something else I could do to prevent this or something I am missing please let me know.
Thanks.
I think you need to convert links to a symbol before passing it to validates_format_of, but since it seems to be working for you, I may be wrong or your sample code above may be missing that detail.
Either way, you can skip validation on blanks with:
validates_format_of :foo, with: some_format, allow_blank: true
I think you're trying to do conditional validation in a roundabout way. Since you really just want to allow blanks, you can do it this way:
class Link < ActiveRecord::Base
Networks = [:facebook, :twitter, :quora, :pinterest]
attr_accessible *Networks
validates_format_of *Networks, :with => URI::regexp(%w(http https)), :allow_blank => true
end

rails multistep form

id like to make a multistep form with rails using the edit and update actions. so i would like it to be like step 1 of the form, and the user fills in his name, address, and phone number. then the user clicks save and continue and he then fills out his shipping address and then clicks save and continue and fills out his billing address. i saw ryan bates version, but its not what im looking for. i would like the order to be saved after the first step so if the user doesnt finish their form, i can call them and ask them what went wrong. can anyone refer me to a tutorial or give me an example of how to make an order form using the edit and update methods?
Typically this means you'll need to put conditions on your model validations. Some subset of your validations should apply to each form page:
class User
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :street, :if => :on_page_two?
validates_presence_of :city, :if => :on_page_two?
validates_presence_of :postal_code, :if => :on_page_two?
validates_presence_of :state, :if => :on_page_two?
validates_presence_of :country, :if => :on_page_two?
validates_acceptance_of :terms_and_conditions, :if => :on_page_three?
def on_page_two?
# whatever you need to determine the page number
end
def on_page_three?
# whatever you need to determine the page number
end
end
It's not pretty but I highly recommend a pattern like this. Anything more complicated and you'll need to rewrite it when your signup flow changes.
There are different approches to this problem.
My particular prefered solution is to implement something like a "State Machine" in the model. This way, I can persist the progress of a, per example, a multistep form, without having to hasle with more actions than new/create and edit/update.
I'm currently working on a heavy long State Machine application using the State Machine gem for rails.
Hope it helps you!
There's a great Railcast on creating multi-step wizard forms, which you can find here. It uses the Wicked gem.

Rails validation problem

I've got a User model with three fields, :email, :display_name and :handle. Handle is created behind the scenes from the :display_name.
I'm using the following validations:
validates :display_name, :presence => :true, :uniqueness => { :message => "Sorry, another user has already chosen that name."}, :on => :update
validates :email, :presence => :true, :uniqueness => { :message => "An account with that email already exists." }
I use the handle as the to_param in the model. If the user fails the validation by submitting a :display_name that already exists, then tries to change it and resubmit the form, Rails seems to use the new handle as the validation for the email -- in other words, it assumes that the email doesn't belong to the current user and validation on the email then fails. At this point, Rails assumes that the changed display name/handle is the one to use for the look up and the update action can't complete at all, because it can't find the user based on the new handle.
Here's the update method:
def update
#user = User.find_by_handle(params[:id])
#handle = params[:user][:display_name]
#user.handle = #handle.parameterize
...
end
This problem doesn't happen when the validation first fails on a duplicate email, so I'm assuming it's something about the way I've written the update method -- maybe I should try setting the handle in the model?
maybe I should try setting the handle in the model?
^ This.
The controller isn't the place to do something like this. If it's model logic that's happening behind the scenes, beyond the user's control, why put it in controller code?
Do it instead in a before_save filter, which is guaranteed to run only after the chosen display name is determined to be available and the record is deemed valid. In this way the handle won't be changed on the cached record until it is actually committed to the db, eliminating the problem of the incorrectly generated URL.
before_save :generate_handle
...
def generate_handle
self.handle = display_name.parameterize
end

Flash[:error] based on validates_uniqueness_of :login, :email

I have a user model that validates_uniqueness_of :login, :e-mail. When a user enters his information into user/new.html.erb, the create action may fail because of either of the two fields.
How can I customize my flash to be more helpful to the user, telling them which (or both) of the fields they need to change the next time around?
flash[:error] = #user.errors.full_messages.to_sentence
should do the job. But I would recommend that you display the error right next to the field which contains invalid data. Plugins like formtastic will do this for you automatically.
Check the API for more ideas.

Resources