0

Trying to create a custom validation method but getting an error

wrong number of arguments (0 for 1..3)

I want to validate the format of a postcode but provide a custom error message as opposed to the message i get if i was to do this

validates_format_of :postcode, with: /\A^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$\z/i, message: 'Please check your postcode'

This will give an error message of

postcode Please check your postcode

So i though i could do this

class User < ActiveRecord::Base
validate :format_postcode

 def format_postcode
  regexp = /\A^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$\z/i
   if !postcode.match(regexp)
     errors.add[:base] << "Please check your Postcode"
   end
 end
end

But this is throwing the error

What am i doing wrong here?

Thanks

1 Answer 1

1

The problem is this line

errors.add[:base] << "Please check your Postcode"

it should be

errors.add :base, "Please check your Postcode"

As the error message suggests, add is a method that takes 1..3 arguments, not a getter for an array.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, silly error there really... thanks for pointing that out, i ended up using errors[:base] << "Please check your Postcode"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.