0

I want to check input and want to show error if input is empty or entered continuous space. just one space allowed between words. e.g:

Test ok test

var pattern = /\s\s+/g;

$('a').click(function() {
  if ($('input').val().length <= 2 || pattern.test($('input').val())) {
    alert('error');
  } else {
    alert('ok go');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type="text"/>

It seems working, but it have issue, do this to find this issue:

Enter 5 space continuously, then click on check, it alert error but click again on check, it alert ok.

should error when user entered more than 2 space continuously.

2 Answers2

0

you can use trim method which will work better than your code in the if statement .

The trim() method removes white space from both ends of a string which in this case the value of the input , after that you can check if its equal to the empty string and will work fine

see the example below

var pattern = /\s\s+/g;

$('a').click(function() {
  if ($('input').val().trim()==='') {
    alert('error');
  } else {
    alert('ok go');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type ="text" />
mostafa tourad
  • 4,308
  • 1
  • 12
  • 21
0

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test:

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property).

The problem is after your regex is matched against the string, the lastIndex property will cause the next match to start after the previous match. You can verify this by outputting the value of pattern.lastIndex after each click.

You can fix this by manually setting lastIndex back to zero after each match, like

$('a').click(function() {
  pattern.lastIndex = 0;
  if ($('input').val().length <= 2 || pattern.test($('input').val())) {
    alert('error');
  } else {
    alert('ok go');
  }
});

You can also fix by getting rid of pattern all together and writing

$('a').click(function() {
  if ($('input').val().length <= 2 || /\s\s+/g.test($('input').val())) {
    alert('error');
  } else {
    alert('ok go');
  }
});

Note that you can change your pattern to /\s{2,}/g matching whitespace two or more times.

ericw31415
  • 415
  • 6
  • 17