From 84d684804b88ec4977f5083c2283417fff7a7b39 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 8 Mar 2016 19:54:03 -0600 Subject: [PATCH] Add Custom Validation Message as a rails til --- README.md | 1 + rails/custom-validation-message.md | 31 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 rails/custom-validation-message.md diff --git a/README.md b/README.md index 57d4d39..7d07376 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,7 @@ _358 TILs and counting..._ - [Code Statistics For An Application](rails/code-statistics-for-an-application.md) - [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md) - [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md) +- [Custom Validation Message](rails/custom-validation-message.md) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) - [Migrating Up Down Up](rails/migrating-up-down-up.md) diff --git a/rails/custom-validation-message.md b/rails/custom-validation-message.md new file mode 100644 index 0000000..94bb619 --- /dev/null +++ b/rails/custom-validation-message.md @@ -0,0 +1,31 @@ +# Custom Validation Message + +When using Rails validations, a standard error message will be provided +whenever there is a violation. Consider the scenario when there is a +uniqueness validation on the email attribute and it is violated: + +```ruby +# User model +validates_uniqueness_of :email + +# Users controller +new_user.errors.full_messages +#=> ["Email has already been taken"] +``` + +Sometimes you don't want the default validation message. The validation +declaration can be given a `message` option to specify an alternate +validation message. + +```ruby +# User model +validates_uniqueness_of :email, message: 'is not available' + +# Users controller +new_user.errors.full_messages +#=> ["Email is not available"] +``` + +Keep in mind that `full_messages` will prepend the model name to the front +of the message. You'll want to ensure that the resulting message is +coherent.