joost / phony_rails

This Gem adds useful methods to your Rails app to validate, display and save phone numbers. It uses the super awesome Phony gem (https://github.com/floere/phony).
MIT License
554 stars 111 forks source link

Add possibility to return original phone number when is not valid #190

Closed synion closed 5 years ago

synion commented 5 years ago

The purpose of this PR is to add ability to return original phone number while using both validates_plausible_phone and phony_normalize.

Original behavior: When both validates_plausible_phone and phony_normalize are defined in the model, validation runs first, and then the number is normalized. However, when the number is invalid, the altered number is returned, so users might be confused that the form shows something different than they typed.

New behavior: I added a new flag normalize_when_valid (disabled by default), which allows to return the original phone_number when is the object is not valid. When phone validation fails, normalization is not triggered at all.

Example usage:

class NormalizabledPhoneHome < ActiveRecord::Base
  validates_plausible_phone :phone_number
  phony_normalize :phone_number, country_code: :country_code, normalize_when_valid: true
end

Filling in the number will result with following:

  1. When the number is incorrect (e.g. phone_number: '+44 888 888 888' for country_code 'PL'), the original validation behavior is preserved, but if the number is still invalid, the original value is returned.
  2. When number is valid, it will save the normalized number (e.g. +48 888 888 888 will be saved as+48888888888).
coveralls commented 5 years ago

Coverage Status

Coverage increased (+0.008%) to 99.826% when pulling 72b7c679d8c55eb13aea9de345e780300fe5b9d5 on synion:normalize_phone_number_when_valid into b69a931d0718399b8435993a8c5d30ff4dd9f884 on joost:master.

coveralls commented 5 years ago

Coverage Status

Coverage increased (+0.008%) to 99.826% when pulling 72b7c679d8c55eb13aea9de345e780300fe5b9d5 on synion:normalize_phone_number_when_valid into b69a931d0718399b8435993a8c5d30ff4dd9f884 on joost:master.

coveralls commented 5 years ago

Coverage Status

Coverage increased (+0.008%) to 99.825% when pulling 834f01ea934a0b7915b070eebe6f24573ce3d737 on synion:normalize_phone_number_when_valid into b69a931d0718399b8435993a8c5d30ff4dd9f884 on joost:master.

joost commented 5 years ago

Thanks. Can you add above notes to the README? Then it is also documented.