0

I want to validate the phone number field and it should accept the valid phone number entries only.

e.g:

  1. if I enter phone number as 337485552599 it should automatically replace the phone number as 07485552599

  2. if I enter phone number as 00337485552599 it should automatically replace the phone number as 07485552599

2
  • you can use regex for it and can format the number as you wish. Commented Sep 8, 2015 at 9:48
  • @Tushar: Can you please post the regex code if you have so it would be useful for others as well.
    – Akash
    Commented Sep 8, 2015 at 9:51

1 Answer 1

0

The best way to do this is using a trigger, but there are several considerations based on the problem you've described...

Validation

If you know exactly how many digits all your phone numbers will be then this isn't a problem, you simply need to check for the right number of characters, but I know of several countries (France included, which by the +33 dialling code is where I am guessing you are from) whose phone numbers can have a varying number of digits. In the UK, both 9 and 10 digit (excluding prefixes) are valid, which means unless you are checking against a database you may run into some problems.

Replacement

Replacing parts of the phone number sting is trivial as long as you know exactly which characters to replace, but as described above if the number is not n digits long, you will have some issues.

Solution

If you just want the two particular cases you gave in your question to be covered, the following code will suffice:

trigger PhoneReplace on Account (before insert) {

    for (Account a : trigger.New) {

        if (!String.IsBlank(a.Phone)) {
            if (a.Phone.startsWith('0033')) {
                a.Phone = '0' + a.Phone.right(a.Phone.length() - 4);
            } else if (a.Phone.startsWith('33')) {
                a.Phone = '0' + a.Phone.right(a.Phone.length() - 2);
            } 
        }

    }

}
2
  • Thanks a lot friends for your valuable solutions. Could you please tell me how would I elaborate the above trigger if I need to check the phone length is 10 digit only followed by 0? I also need to replace '+' with 0(if phone number start with +) and '+91' with 0. (if phone number start with + followed by country code)
    – Akash
    Commented Sep 8, 2015 at 10:45
  • To get rid of special characters such as '+', you can use the replace(target, replacement) method using '+' as the target. I would advise using an empty string ('') as the replacement value, as there is more that can go wrong the more characters you individually replace. Check out the documentation for String methods for more info.
    – leylandski
    Commented Sep 8, 2015 at 10:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .