0

There are several ways to check if a input is empty, for example:

$('input:text').val().length == 0

My problem is that i found no solution how to check if the input is empty or blank? How can i check this is there some regex?

Thanks

Prashobh
  • 8,758
  • 14
  • 59
  • 90
John Smith
  • 5,721
  • 12
  • 49
  • 101
  • 5
    Don't forget to `trim()` it. – biziclop Feb 19 '14 at 08:51
  • 1
    possible duplicate of [How do you check for an empty string in JavaScript?](http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – Yehuda Shapira Feb 19 '14 at 08:52
  • biziclop is right, just do `$('input:text').val().trim().length == 0` – tewathia Feb 19 '14 at 08:53
  • 1
    If you are not explicitly looking for a jquery solution, input has a pattern attribute which you can use. The regex is the same as javascript's – andrei Feb 19 '14 at 09:11
  • @schopy could you please explain it further? – John Smith Feb 19 '14 at 09:15
  • 1
    @JohnSmith Basically you can have client-side form validation without using js on modern browsers. You can have a look at the Constraint Validation chapter at https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms_in_HTML – andrei Feb 19 '14 at 09:22

2 Answers2

0

you can use jQuery.trim() to trim your input first:

var value = $('input:text').val(); 
if ($.trim(value) == '') { /* Empty or blank */ }
Pavel Štěrba
  • 2,651
  • 2
  • 23
  • 46
0

You can remove white spaces before checking empty:

if ($("input:text").val().replace(/^\s+|\s+$/g, "").length == 0){
Milind Anantwar
  • 79,642
  • 23
  • 92
  • 120