3

I am trying to use jquery for validating forms.

This is the pattern that is allowed in a text box for a user.

var pattern = /^[a-zA-Z0-9!#$&%*+,-./: ;=?@_]/g;

If the user types anything else other than this then that has to be replaced with a "".

$(document).ready(function() {
  $('#iBox').blur(function() {
     var jVal = $('#iBox').val();
  if(jVal.match(pattern)) {
   alert("Valid");
  } else {
   alert("New "+jVal.replace(!(pattern),""));
                }
    });
  });
});

But the replace function does not work this way.

1 Answer 1

5

Use a negated character class by writing a ^ immediately after the opening square bracket:

/[^a-zA-Z0-9!#$&%*+,-./: ;=?@_]/g

Here the ^ has a special meaning that is different from the normal meaning it has in regular expressions (normally it matches the start of the line).

So your corrected code would look like this:

var pattern = /[^a-zA-Z0-9!#$&%*+,-./: ;=?@_]/g;
// ...
alert("New " + jVal.replace(pattern, ""));

Also note that calling replace doesn't actually change the original string - it returns a modified copy of the string. If you want to modify the value of jVal you will need to reassign to it:

jVal = jVal.replace(pattern, "");
Sign up to request clarification or add additional context in comments.

2 Comments

Just to be clear to the asker, you should do this, then simply call replace(pattern, "") - the problem of course is that by boolean-negating pattern, it's essentially passing false to replace instead of the RegExp.
@Ken Franqueiro: Thanks, added.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.