2

I need to block special character except comma. So I am using code given below. Its is working but it is also removing space between two words. fiddle

var chars =/[(,\/\w)]/i;
$('input').keyup(function(e) {
  var value = this.value;
  var char = value[value.length-1];
    if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){

  if (!chars.test(char)) {
      $(this).val(value.substring(0, value.length-1));
  }
    }
});
3
  • Can't you just include the space in your character class? i.e., [ (,\/\w)]/i (It now starts with a space). Commented Apr 29, 2014 at 14:26
  • @PA. Adding the space does "work", since his code removes the last character of the input when it does not match his regexp. Although he also allows (, ), and /. Not sure if that's part of the plan. And if you type fast enough characters will not be removed anyway :) Commented Apr 29, 2014 at 14:31
  • 1
    And no reason to use the i modifier here either =) Commented Apr 29, 2014 at 14:33

2 Answers 2

2

In terms of usability, manipulating the user's input as they're typing can be very frustrating. In addition, if the user types fast enough it doesn't work anyway (as mentioned by Daniel Knippers, above)

A better bet would be to validate the user's input and let them know in real-time if the input is invalid.

Try this code:

var regex =/^[\w\s\,]*$/i;
$('input').keyup(function(e) {

    var message = regex.test(this.value) ? "" : "Error";
    $('#message').html(message);
});

jsFiddle version

Sign up to request clarification or add additional context in comments.

Comments

0

as far as i am understood, you wants that space should be allowed in txt box so,

here is your ANSWER

you need to add space after \w

var chars =/[(,\/\w )]/i;
$('input').keyup(function(e) {
  var value = this.value;
  var char = value[value.length-1];
    if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){

  if (!chars.test(char)) {
      $(this).val(value.substring(0, value.length-1));
  }
    }
});

please note that i have added space after \w, so the regexp is var chars =/[(,\/\w )]/i;

1 Comment

@anni I don't know how typing in ALL CAPS relates to vocabulary?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.