0

When I type in my input the text appears on image. I want to make the code work like that:

When user types character that is recognized by regex then place it on image else just throw some error or do not let it type at all in the input field.

This is the regex: [A-Z0-9a-z&,.-/()@*+!?"':; -]

I'm trying to achieve it like this:

$("#firstText").keyup(function () {
  var value = $(this).val().toUpperCase();
  var regex = "[A-Z0-9a-z&,.-/()@*+!?"':; -]";

  if(regex.test(value))
  {
    $(".zetin16").text(value);
  } else {
    alert('this is bad');
  }
});

But I get this error: Uncaught SyntaxError: Invalid or unexpected token

In this line: var regex = "[A-Z0-9a-z&,.-/()@*+!?"':; -]";

Thanks in advance for any help.

UPDATE

The regex working fine now. Now I want to prevent typing characters in input when regex doesnt match the character. This is my code currently:

$("#firstText").keyup(function(e) {
    var value = $(this).val().toUpperCase();
    var regex = new RegExp(/[A-Z0-9a-z&,.-/()@*+!?"':; -]/);

    if (regex.test(value)) {
        $(".zetin16").text(value);
    } else {
        e.preventDefault();
        return false;
    }
});
rrk
  • 15,677
  • 4
  • 29
  • 45
feknuolis
  • 11
  • 3

3 Answers3

2

With regex, use the forward slash as delimiter. If a forward slash occurs as a literal inside the regex itself, escape it:

var regex = /[A-Z0-9a-z&,.-\/()@*+!?"':; -]/;

Reference: JavaScript regex replace - escaping slashes

(The problem with the original string was that it contained a double quote, and was delimited using double quotes at the same time).

Community
  • 1
  • 1
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
1

The exact error you're seeing is because you are defining the variable as a double quoted string, with an unescaped double quote in it.

It shouldn't be a string anyway. It should be a regular expression like this.

var regex = /[A-Z0-9a-z&,.-/()@*+!?"':; -]/;
JAAulde
  • 19,250
  • 5
  • 52
  • 63
rrk
  • 15,677
  • 4
  • 29
  • 45
  • Okay I dont get any error now. But is there are some function that prevents typing characters that are not available by regex ? :) – feknuolis Jun 16 '16 at 16:10
  • @feknuolis [This](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) could help. – rrk Jun 16 '16 at 16:14
  • @feknuolis or [this](http://stackoverflow.com/a/19111723/1479535) – rrk Jun 16 '16 at 16:17
0

try using this pattern for using regular expression

var regex = "['A-Z0-9a-z&,.-/()@*+!?':; -]";

var reg =new RegExp(regex)

var val ="asss"

reg.test(val)
Vicky Kumar
  • 1,358
  • 1
  • 14
  • 26