开发者

Validation regex format, allowing spaces on entry but removing them when saving record

The following regex validates a phone number(could have been anything else though), allow开发者_JAVA技巧ing trailing spaces:

validates :phone, 
          :presence => true,
          :format => {:with => /\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}[ ]*\z/}

The reason I want to allow spaces at the end is simple because some users may type it by mistake.

What I want to be able to do is, allow those spaces during validation, but when saving the record, strip away any leading/trailing spaces. In this way, I can allow the user to make a small "mistake" (i.e. spaces at the end) but still save a "completely valid" value (in this case a phone number) saved to the database.

Can this be done automatically (for any model, any field) so that I don't have to specifically trim each field before saving it ?


If you're only doing this for a few fields, the easiest way to accomplish it would be with custom setters:

def phone_number=(val)
    self[:phone_number] = val.rstrip
end

But if you want a more generic, use-anywhere setup, I'd suggest writing an ActiveRecord extension - something along the lines of:

class ActiveRecord::Base
    def self.strips_trailing_spaces_from(*attrs)
        @@sts_attrs ||= []
        @@sts_attrs << attrs
        before_save :strip_trailing_spaces
    end

    def strip_trailing_spaces
        @@sts_attrs.each do |attr|
            val = self[attr]
            self[attr] = val.rstrip if val.is_a?(String)
        end
    end
end

And then for every model you want to use this, you can simply call (Rails "macro" style):

class MyModel < ActiveRecord::Base

    strips_trailing_spaces_from :phone_number, :name, :pizza, :etc

    # ...classy stuff...
end

Note - this code hasn't been tested, but it should get idea across. Hope it helps!


# strip leading and trailing whitespace in s
# ... simply:
s.strip!                   # modify s
s.strip                    # return modified string
# ... or with a regex
s.gsub!(/^\s+|\s+$/, '')   # modify s
s.gsub(/^\s+|\s+$/, '')    # return modified string
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜