Reputation: 28392
I am providing a web service to be called by external companies. The required data covers several models including person, address etc. I want to validate the received data conditionally based upon some fields within the request. I will eventually have many differing sets of validation data, although currently I only have one and I am about to add the second.
My current model looks something like this
class Person < ActiveRecord::Base
validates_length_of :first_name, :within => 1..32, :allow_blank => true
...
...
end
Conceptually my model now needs to do something like this.
class Person < ActiveRecord::Base
validate :first_name?
def first_name?
if country == 'UK'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
else if country == 'DE'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
end
end
This would obviously work fine for 2 companies/countries but will not work well as the number of companies and/or countries increases. I am now considering keeping the validation data either in the database or in a YAML file and then performing the validations manually for each field based upon the minimum, maximum, format values stored externally from the model.
I am thinking that I could store the validation data in a structure similar to the following
country: UK companyname: ABC field: first_name minimum_length: 2 maximum_length: 20 required: true field: middle_name minimum_length: 1 maximum_length: 10 field: email_address minimum_length: 10 format: /someregexforemail addresses/ companyname: DEF field ... country: DE companyname: XYZ field: ....
and so on.
I could then load this validation data and use this within my own hand-rolled validator.
Has anyone done similar things in the past and what methods did you use? I am particularly interested to know how you approached the following.
Upvotes: 0
Views: 1589
Reputation: 15596
I did something similar with phone numbers. Your approach is very similar to what I did myself. To answer your questions:
Did that help you?
Upvotes: 1