Regex email : number + format of email in ruby - ruby-on-rails

I have a field email in my database also call emails that should have this format : 123456789#pac.gmail.com where 123456789 should be numbers and a length of 9.
In my model, I tried to format this for my user with the following code :
class Email < ApplicationRecord
EMAIL_PATTERN = /^[0-9]+/#pac.gmail.com
LENGTH = 9
validates :email, presence: true, format: EMAIL_PATTERN, length: LENGTH
end
But with that I have an error unexpected tIVAR, expecting end but I don't get why should I have a END in my code as I don't start any loop or something,
Is anyone knows how to format the email in the right way and why I have this kind of error ?

There is no need to separately check the length; you can do that from within your regex. If I'm understanding correctly, you want to make sure there are 9 digits followed by #pac.gmail.com. You can do it like this:
class Email < ApplicationRecord
EMAIL_PATTERN = /\A[0-9]{9}#pac.gmail.com\z/
validates :email, presence: true, format: EMAIL_PATTERN
end

Related

Rails ActiveRecord - field vallidation

I am new to rails and in my models am doing some field validation and i need some help
has_many :stats
validates :name, presence: true, uniqueness: true, length: { minimum: 2 }
validates :age, presence: true
validates :title, presence: true, format: { with: ???????????????
message: "must begin with abc_ and have numbers after" }
I am stuck trying to validate title to be in the format abc_8943578945794
Is this where I should really create a method to validate?
Thanks, Nigel.
Apparently you're looking for a regular expression to match the title, try this:
with: /^[a-z]+_[0-9]+$/
Fernando Almeida's anwers is right, you need a regex to match the expected value, but for the format that "OP" have passed (abc_8943578945794), this seems more suitable:
/^[a-z]{3}_[0-9]{13}$/
The only thing that I'm doing more than his, is setting the number of digits (3) and characters (13) that the string should have.
I would use the following regexp:
with: /\Aabc_\d+\z/
Explanation:
\A # beginning of the string
abc_ # string prefix you are looking for
\d+ # one or more digits
\z # end of the string

Regex validation in rails

I am new with rails and I am trying to register my user's names without special characters and spaces but allowing the - symbol.
Example :
##Pierre! => invalid
Pierre-Louis => valid
Pierre Louis => invalid
In the User.rb file I have :
class User < ApplicationRecord
...
validates :first_name, presence: true, length: {maximum: 25}, format: {with: Regexp.new('[^0-9A-Za-z-]')}
...
I don't have any error message and I'm still able to register using special characters.
Also, I'd like to add an error message if the name isn't validated.
Do you have any leads ?
Any help would be much appreciated !
When you validate format with regex, you need to ensure you match the whole string that is being validated. In order to do that your regex needs to start with \A and end with \z that are anchors marking beginning and ending of the string.
In your case:
validates :first_name,
presence: true,
length: {maximum: 25},
format: {with: /\A[-0-9A-Za-z]\z'/}
message: "Custom message"
assuming you accept numbers, small and big letters and a minus sign.

client_side_validations and callbacks

I have a model with fields that are validated frontend with client side validations gem.
My problem is for the below field (European VAT number for France) :
validates :VAT, length: { maximum: 15 }
validates :VAT, format: { with: /\A[a-zA-Z]{2}\d{0,13}\z/ }
Also I have this callback in order to normalize it before validation :
before_validation :normalize_vat
def normalize_vat
if self.VAT.present?
self.VAT[0]=self.VAT[0].capitalize
self.VAT[1]=self.VAT[1].capitalize
self.VAT = self.VAT.delete(' ')
end
end
This callback capitalize letters and strips the spaces that a user could have input such as :
FR 333 3333 333333
Though it seems client_side_validations is not picking the callback frontend...
I could change the regexp to match any spaced input but it wrecks a bit my validations as I can't validate length no more for example ...
Would there be a trick to fix this ?

Cannot iterate over unique elements

I have an array of errors as below:
n.errors.full_messages
# => ["Password can't be blank", "Password can't be blank", "Password is too short (minimum is 3 characters)"]
I would like to iterate over the unique elements of this array and display them on the screen.
Validation model
class Member < ActiveRecord::Base
has_one :profile
before_save { self.username = username.downcase }
has_secure_password
validates :password, presence: true, length: { minimum: 3 }
end
n.errors.full_messages.uniq do |a|
puts a
end
uniq is not working, and "Password can't be blank" appears twice in my array. Any ideas?
Password can't be blank
Password can't be blank
Password is too short (minimum is 3 characters)
# => ["Password can't be blank"]
Edit: This doesn't actually answer the question, use the answer from #BroiSatse if google brought you here.
The reason you are getting that message twice is because of has_secure_password:
http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password
The first bullet point appears to add validation that makes the password required.
In your model you also add
validates :password, presence: true, length: { minimum: 3 }
The presence: true part of this adds the same validation. Remove this so its:
validates :password, length: { minimum: 3 }
This should fix the problem.
uniqe with a block uses value of the block to compare the elements. What you want is:
n.errors.full_messages.uniq.each do |m|
Anyhow, I think you're approaching the problem from the wrong angle - your problem is not how to avoid displaying duplicate messages, but how this duplication happened.
You could just do a string comparison.
Have the array that is problematic to you. Go over it and save the elements one by one to a new array.
Now when the first one is added to the new array, check that the elements allready in the array don't match the new element to be added. E.g: "My string".eql? "My sting"
There might be of course a more clever way to do this in Ruby. But that would be the idea when doing it in other languages manually.

rails 4 validates presence and length on the same parameter

Is it a good idea to having validates like this:
validates :serialnumber, presence: true, length: {7..20}, format: {with: /\d{7,20/}
As you see it generates three errors if I don't type serialnumber.
I would like to see only one error.
If I type nothing, I would like to see 'serial number is required' only.
If I type 123ABC I would like to see 'wrong length' only
And if I type 123-ABC-123 I would like to see 'wrong format' only
How to do it?
Regards
You could split it into 2 validators, check if this would work
validates :serialnumber, presence: true
validates :serialnumber, length: {7..20}, format: { with: /\d{7,20}/ }, allow_blank: true
As I understand then you want to see only one error message at a time. If that's the case then custom validation method might help. For ex.
validate :serial_number_validation_one_by_one
private
def serial_number_validation_one_by_one
if !self.serial_number.present?
errors.add(:serial_number, "must be present!")
elsif self.serial_number.length < 7 || self.serial_number.length > 20
errors.add(:serial_number, "must have length between 7 and 20!")
elsif self.serial_number.match(<your regex pattern here>)
errors.add(:serial_number, "must be properly formatted!")
end
end
Keep in mind that custom validation methods are called by validate not by validates.

Resources