Setting Custom error message with CarrierWave

2019-02-06 08:32发布

问题:

I have an Image uploading application running on carrierwave which restrict user from uploading image only of desired extensions 'jpg,jpeg,png' I have put in place the validation for carrierwave in my Uploader define as

def extension_white_list
  %w(jpg jpeg png)
end

Now anyone trying to upload image having extension different from the desired extension(mention above) will result in validation errors

I want to customize the Validation Error message

Right Now Error message is presented as

You are not allowed to upload "" files, allowed types: ["jpg","jpeg","png"]

Can anyone help I found this link where the guys mention how to achieve this

but it some problem

1. I18n support I dont require to translate the error message using I18n 

2. The 'Key' to be used I not sure which key to used in YAML for
    not matching extension whitelist error message (e.g) carrierwave_processing_error key if error is for processing failure

Please Provide me answer in term of CarrierWave and please dont ask me to write separate validation set for extension matching

回答1:

Actually it is:

en:
  errors:
    messages:
      extension_white_list_error: "You are not allowed to upload %{extension} files, allowed types: %{allowed_types}"

Source:

https://github.com/jnicklas/carrierwave/blob/master/lib/carrierwave/locale/en.yml



回答2:

If someone ends up here in 2016+ and wonders why correct answers found on this page or anywhere else in the web do not work, it could be because of this. At least it was in my case:

Rename extension_white_list ~> extension_whitelist

Easy thing to miss when just copying solutions.

https://github.com/carrierwaveuploader/carrierwave/commit/06003a5044190f93d07d958b6ca9fd6f6f8fbdb2



回答3:

define a key value pair in en.yml

en:
  errors:
    messages:
       extension_white_list_error: 'My Custom Message'

If has changed with recent versions. So try as below if above answer doesn't work:

en:
  errors:
    messages:
       extension_whitelist_error: 'My Custom Message'

and let CarrierWave do the rest



回答4:

for some reason my ActiveModel did not include the validation module from carrierwave upon calling mount_uploader. I had to do include CarrierWave::Validations::ActiveModel in my model to get the integrity validator.