0

In sign up page I want to validate user's email if user enter invalid email or email textbox left blank and want to show error message Enter your email address

My User Model:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
            uniqueness:  { case_sensitive: false }

With the above regex, I am validating email but do not know how to add and display error meesage.

Kindly help me. Thanks.

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85

2 Answers2

2

Just try:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, 
          :presence => {:message => "Enter your email address!" },
          :format => { :with => VALID_EMAIL_REGEX, :message => "Enter a valid Email address !"}
          :uniqueness => {:case_sensitive => false, :message => "Email already exists!"}

To view these error, use the default error helper provided by Rails (<%= f.error_messages %> ).

<%= form_for @user, :url => {:controller=>"users", :action => "sign_up" } do |f| %>  
   <%= f.error_messages %> 
   ---form fields and contents --
<%end%>

Hope it helps :)

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
0

For the Error Message,you can simply add message: 'your message'Just do like this.

If you want to provide a separate Error Messages,then you have to split the validations.

validates :email, presence: true, :format=> { :with=> VALID_EMAIL_REGEX , :message=> 'Enter your Email Address' }

validates :email, uniqueness: {:case_sensitive => false, :message => 'Please provide a valid Email' }
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • but it give me error "Unknown validator: 'MessageValidator'" at this line "validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, message: 'Enter your Email Address'" – user3463868 Apr 03 '14 at 05:55
  • @user3463868 Which Rails version are you using? – Pavan Apr 03 '14 at 05:59