KodeFor.Me
KodeFor.Me

Reputation: 13511

Allow certain characters in text field with regex

I have done a long time research on how to allow only three certain characters to be allowed in text field by using regex but I cannot fine a solution.

The way I try is to replace any character that it is not +, (, ), (space) or a digit.

The regex I have try are the following:

(^[\+\(\)\s0-9]+)

but doesn't work. I don't know if I am wrong.

I understand the above regex as : If there string contains a character that ^ it is not +, (, ), or a digit between 0-9

and then in my Javascript I do the following :

var $text  =   $('#text_field');

if(0 < $text.length)
{
    $text.on(
        'keyup',
        function(e)
        {
            var $val = $(this).val();

            $val = $val.replace(/(^[\+\(\)\s0-9]+)/, '');

            $(this).val($val);
        }
    );
}

but unfortunately this doesn't work.

Can somebody help me please ?

I also have try the following :

^(^[\+\(\)\s0-9]+)$
(^[\+\(\)\s\d]+)
^(^[\+\(\)\s\d]+)$

but still don't work.

Upvotes: 0

Views: 130

Answers (2)

nu11p01n73R
nu11p01n73R

Reputation: 26667

You shoud move the ^ into the character class.

That is

/[^\d)(+ ]/
  • [^\d)(+ ] Negated character class. Matches any character other than the one in the class.

Outside the character class ^ acts as an anchor, which matches the begining of the string. Once it is moved into the character class it negates thus matching the reverse.

Test

"asdf123(+123) 1234asdf".replace(/[^\d)(+ ]/g, "");
=> 123(+123) 1234

Regex Demo

Upvotes: 2

Augustin
Augustin

Reputation: 2612

The problem is you need to have the ^ inside the square brackets. Also, you should run it globally, hence replace(/([^\+\(\)\s0-9]+)/g, "") should work.

Upvotes: 2

Related Questions