Masking input with optional alphabet prefix to a p

2019-07-14 17:39发布

问题:

I know of this nice jquery plugin: http://digitalbush.com/projects/masked-input-plugin/ for Masked input, and I can use it fine.

So let's say I want a field to be masked by this format: +999 9 999 9999 That's fine, and it's working.

The issue is that sometimes within the field, my users also have the option of giving some text before the number.

So the two inputs that are valid for a user are:

  • +999 9 999 9999
  • any optional alphabet letters and special characters (but not digits!) +999 9 999 9999,

So for example, this is a valid user input: +966 1 484 1122.

And this is also a valid user input: Phone #: +966 1 484 1122.

How can I make this mask?

Edit

For the second type of input, there are actually a finite number of alphabetical prefixes possible, like these:

  • Phone: +999 9 999 9999
  • Phone +999 9 999 9999
  • Phone # +999 9 999 9999
  • Phone #: +999 9 999 9999
  • Call: +999 9 999 9999
  • Call me: +999 9 999 9999
  • Call +999 9 999 9999
  • Telephone +999 9 999 9999
  • Telephone # +999 9 999 9999
  • Telephone: +999 9 999 9999
  • Talk +999 9 999 9999
  • Contact: +999 9 999 9999
  • Contact # +999 9 999 9999
  • Contact #: +999 9 999 9999

Basically, just the usual possible ways of telling users to "call" at a given number. For this problem, let's assume the prefix can only be the above words. So that means the format for the prefix is usually Call|Contact|Talk|Phone|Telephone, optional #, optional :.

And the overall mask is something like: optional Call|Contact|Talk|Phone|Telephone optional # optional : +999 9 999 9999

回答1:

Use the following regular expression:

var phone_mask = /^[^0-9]*\+9{3}\s9\s9{3}\s9{4}$/;

phone_mask.test("Phone: +999 9 999 9999")
phone_mask.test("Phone +999 9 999 9999")
phone_mask.test("Phone # +999 9 999 9999")
phone_mask.test("Phone #: +999 9 999 9999")
phone_mask.test("Call: +999 9 999 9999")
phone_mask.test("Call me: +999 9 999 9999")
phone_mask.test("Call +999 9 999 9999")
phone_mask.test("Telephone +999 9 999 9999")
phone_mask.test("Telephone # +999 9 999 9999")
phone_mask.test("Telephone: +999 9 999 9999")
phone_mask.test("Talk +999 9 999 9999")
phone_mask.test("Contact: +999 9 999 9999")
phone_mask.test("Contact # +999 9 999 9999")
phone_mask.test("Contact #: +999 9 999 9999")

Here is a commented breakdown of the regular expression:

var phone_mask = RegExp("^[^0-9]*"/* Optional non-numeric characters */ +
                        "\\+9{3}" /* Followed by a plus sign and three nines */ +
                        "\\s9"    /* Followed by a space and one nine */  +
                        "\\s9{3}" /* Followed by a space and three nines */ +
                        "\\s9{4}" /* Followed by a space and four nines */ +
                        "$");