How to remove Field Name in validates_presence_of on rails Model for the following coding
validates_presence_of :address, :attributes => true, :discard_if => :invalid?, :on => :save, :message=> "Invalid Address"
and the Output is
Address Invalid address
and I don't want Address field in this validation
Please Help me to solve this problem
I believe this is the answer you're looking for:
Fully custom validation error message with Rails
The standard error format is "%{attribute} %{message}". If you don't want attribute names included in messages, you can change errors.format in your locale.
# config/locales/en.yml
en:
errors:
format: '%{message}'
AFAIK, you can't do this for a single attribute.
I was searching for the same question and stops on:
*instance.errors.add*
for exmpl,
question.errors.add("Answer","can't be blank") if self.body.blank?
There is *errors.add_to_base*, but just add is working more comfortably, for my opinion.
Related
At the moment, if I leave a field in the form blank, I get an error message that is written in the en.yml file, how can I overwrite this error message in the model?
class Contact < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :message, :validate => true
attribute :nickname, :captcha => true
This is what I've tried for the name attribute but I'm still getting the error message which is written in the en.yml file. I can't change the error message from en.yml as it is for another part of my application.
validates :name, presence: { message: "Can't be blank" }
Any ideas why this is not overwriting the message?
You can customize the error message using i18n localization in the same way that you would for a regular ActiveRecord model. The only difference is that you use the mail_form top-level scope instead of active_record.
# en.yml
mail_form:
errors:
models:
contact:
attributes:
name:
blank: "My custom message goes here"
sources:
MailForm i18n Documentation
Translations for ActiveRecord Models
You don't need to nest the message in an inner hash. The syntax for messages on validations is:
attribute :name, validate: true
Not very elegant, but you can set the error message manually:
contact = Contact.new
contact.valid? # => false
contact.errors[:name] = "Can't be blank" # => Will add "Can't be blank to the list of errors associated with name"
Or, if you want to replace the original error:
contact.errors.set(:name, "Can't be blank")
If the above answers are not working (try them out first, rails is good with error messages) you could use JQuery to validate the fields before submit, there is a plugin for that https://jqueryvalidation.org/
From there site
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
When a user tries to create a record with a name that already exists, I want to show an error message like:
name "some name" has already been taken
I have been trying to do:
validates_uniqueness_of :name, :message => "#{name} has already been taken"
but this outputs the table name instead of the value of the name attribute
2 things:
The validation messages use the Rails I18n style interpolation, which is %{value}
The key is value rather than name, because in the context of internationalization, you don't really care about the rest of the model.
So your code should be:
validates_uniqueness_of :name, :message => '%{value} has already been taken'
It looks like you can pass a Proc to the message. When you do this, you get two parameters:
A symbol along the lines of :activerecord.errors.models.user.attributes.name.taken
A hash that looks something like `{:model=>"User", :attribute=>"Name", :value=>"My Name"}
So if you allow for two parameters on a proc, you can use the attributes[:value] item to get the name that was used:
validates_uniqueness_of :name,
:message => Proc.new { |error, attributes|
"#{attributes[:value]} has already been taken."
}
What version of Rails do you use?
If Rails 3. then as i understand you should use :message => '%{value} has already been taken'. I am not sure about Rails 2.3. - but in any case you can create your own custom validation that performs what you need.
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'
I'm trying to capture the value that's throwing a uniqueness error (or for that matter, any other type of built-in validation) to display it in the :message option. Here's what I tried (didn't work)
# inside the model
validate_uniqueness_of :name, :message => "#{name} has already been taken" # also tried using #{:name}
I could use a custom validation, but this beats the point of using something that's already integrated into AR. Any thoughts? thanks.
Try this interpolation technique:
validate_uniqueness_of :name, :message => "%{value} has already been taken"
The RailsGuide for Active Record Validations and Callbacks shows an example where %{value} is interpolated in a custom error message:
:message => "%{value} is not a valid size"
I looked at the validates_each documentation and can see the validate block is passed three properties: |record, attr, value|. All three can be accessed with %{model}, %{attribute} and %{value}.
While this is limited, since it only gives you access to three properties, thankfully that is all you need.
Try self.name
validates_uniqueness_of :name, :message => "#{self.name} has already been taken" # also tried using #{:name}
Also validate_uniqueness_of is wrong it should be validates_uniqueness_of
If this not works use validate method and comment line validates_uniqueness_of
def validate
name= User.find_by_name(self.name) #Assuming User is your Model Name
unless name.blank?
self.errors.add :base, "#{self.name} has already been taken"
end
end
I have this validation in my user model.
validates_uniqueness_of :email, :case_sensitive => false,
:message => "Some funky message that ive cleverly written"
In my tests I want to ensure that when a user enters a dupe email address that my message definately gets shown but without having to duplicate the error string from above in my test. I dont like that because im sure the message will change as i start thinking about copy. Does rails store these error messages - something which i can call in my tests?
Ive done a general test of
assert #error_messages[:taken] , user.errors.on(:email)
but that would pass on any of the other email related errors ive set validations up to catch i.e. incorrect formating, blank etc.
I made a quick test, and it looks like the error messages are sorted in the order you wrote your validation statements in your model class (top-down).
That means, you can find the error message for the first validation on an attribute at the first place in the errors array:
user.errors.on(:email)[0]
So, if your user model class contains something like this:
validates_presence_of :email
validates_uniqueness_of :email, :case_sensitive => false, :message => "Some funky message that ive cleverly written"
validates_length_of :email
...you'll find your 'funky message' at user.errors.on(:email)[1], but only if at least validates_presence_of triggers an error, too.
Concerning your specific problem:
The only way I could think of to not repeat your error message in the test, is to define a constant in your user model and use this instead of directly typing a message for that validation:
EMAIL_UNIQUENESS_ERROR_MESSAGE = "Some funky message that ive cleverly written"
...
validates_uniqueness_of :email, :case_sensitive => false, :message => EMAIL_UNIQUENESS_ERROR_MESSAGE
In your test, you could use this constant, too:
assert_equal User::EMAIL_UNIQUENESS_ERROR_MESSAGE, user.errors.on(:email)[1]
In rspec,
it "should validate uniqueness of email" do
existing_user = User.create!(:email => email)
new_user = User.create!(:email => existing_user.email)
new_user.should_not be_valid
new_user.errors.on(:email).should include("Some funky message that ive cleverly written")
end