SMPLYJR
SMPLYJR

Reputation: 884

Javascript Regexp - not accepting space but it should

I just want my input to accept only letters and spaces because my input serves for name and this doesn't work I already tried to put some space in the regex. My regex is working but spaces isn't.

// without space
$('#name').on('input', function (e) {
    this.value = this.value.replace(/[^a-zA-Z.,ñÑ ]/g, '');
});

// with space but it didnt work
$('#name').on('input', function (e) {
    this.value = this.value.replace(/[^a-zA-Z .,ñÑ]/g, '');
});

// with space again but it fails work also
$('#name').on('input', function (e) {
    this.value = this.value.replace(/[^a-zA-Z. ,ñÑ]/g, '');
});

Upvotes: 1

Views: 1081

Answers (4)

venkatKA
venkatKA

Reputation: 2399

Use \s for single whitespace. Additionally \s+ for matching multiple whitespaces

Upvotes: 1

Alex Kudryashev
Alex Kudryashev

Reputation: 9480

Use keydown event and cancel when e.which || e.keyCode not in allowed range. Example:

$('#name').on('keydown', function(e){
   var key = e.which || e.keyCode;
   if(allowedKeysArray.indexOf(key) ==-1)
      return false;
});

keydown event in cancelable. keyup, keypressed and input are not. You can exclude numbers and most non-letter characters for sure. Minus - you cannot see characters, codes only.

Upvotes: 0

Michael Gaskill
Michael Gaskill

Reputation: 8042

Try this:

this.value = this.value.replace(/[^a-zA-Z.,ñÑ\su00A0\u2008\u2009\u200A\u200B\u202F\uFEFF]/g, '');

This will identify many Unicode spaces, including the non-breaking space (U+00A0) that can crop up in HTML pages. The others will match formatting spaces. There are more unicode spaces, so if this doesn't work, we can add more codes.

Upvotes: 0

0xdw
0xdw

Reputation: 3842

$('#name').keyup(function() {
  var new_value = this.value.replace(/[^a-zA-Z.\s,ñÑ]/g, '');
  this.value = new_value;
  
  $('#output').html(new_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='name'>

<div id='output'></div>

If you need to skip single whitespace character use \s,so use /[^a-zA-Z.\s,ñÑ]/g instead of /[^a-zA-Z. ,ñÑ]/g.

Upvotes: 1

Related Questions