0

I saw some questions here but no one works for me. This regex should only accept phone numbers. I need to use expressions as strings because I need to get them from a data- attribute.

This is the code:

    $('.valid_mobile').change(function(event) {

    var rex = '^0\d{10}$';
    var message = 'This is not a valid mobile phone number.';

    var text = $(this).val();
    var regex = new RegExp(rex);

    if (! regex.test(text))
    {
        alert(message);
        $(this).val('');
    }
    console.log(regex.test(text));
    console.log($(this).val());
});
rostamiani
  • 2,859
  • 7
  • 38
  • 74
  • 3
    http://stackoverflow.com/questions/10769964/backslashes-regular-expression-javascript or http://stackoverflow.com/questions/6521572/javascript-regex-not-working => `var rex = '^0\\d{10}$';` or `var regex = /^0\d{10}$/` – Wiktor Stribiżew Jul 11 '16 at 08:06
  • Thanks. Then I need double slashes!!! but why? – rostamiani Jul 11 '16 at 08:10
  • 1
    You need double backslashes because in C strings, a backslash is used to define escape sequences. A literal ``\`` is defined as ``\\``, and that is the kind of the backslash a regex engine requires to define shorthand character classes. – Wiktor Stribiżew Jul 11 '16 at 08:11

0 Answers0