How to check if texts are all space characters on the client side?

How to check if there is a user input text for all spaces (space, tab, input, etc.) on the client side?

Thanks in advance!

+48
javascript jquery
Jul 23 '09 at 14:35
source share
8 answers

This question has been flagged by jQuery. In jQuery, you can run the following:

if ( $.trim( $('#myInput').val() ) == '' ) alert('input is blank'); 
+78
Jul 23 '09 at 19:08
source share

/^\s+$/.test(userText)

Change + to * to include an empty string '' as a positive match.

Edit

Most often, although you need to trim the spaces from user-entered text and just check to see if it is non-empty:

 userText = userText.replace(/^\s+/, '').replace(/\s+$/, ''); if (userText === '') { // text was all whitespace } else { // text has real content, now free of leading/trailing whitespace } 
+30
Jul 23. '09 at 14:37
source share

This will also work:

 var text = " "; text.trim().length == 0; //true 
+18
Jul 19 '12 at 17:24
source share

Like this...

 function isEmpty(str) { return str.replace(/^\s+|\s+$/g, '').length == 0; } 
+7
Jul 23 '09 at 14:44
source share

If you want to see if the file contains all spaces or is empty, I would recommend checking the inverse and inverting the result. This way you do not have to worry about special cases around an empty string.

all spaces are the same as without spaces, therefore:

 function isWhitespaceOrEmpty(text) { return !/[^\s]/.test(text); } 

If you do not need empty lines, you can change it a little:

 function isWhitespaceNotEmpty(text) { return text.length > 0 && !/[^\s]/.test(text); } 
+5
Jul 23 '09 at 15:18
source share

Josh's answer is very close to this, but according to w3schools (in May 2014) it looks like this:

 function isEmpty(str) { return str.replace(/^\s+|\s+$/gm,'').length == 0; } 
+3
May 28 '14 at 10:38
source share

To find spaces generated by JavaScript between elements, use:

 var trimmed = $.trim( $('p').text() ); if ( trimmed === '' ){ //function... } 
+2
Nov 01 '16 at 23:57
source share

Something that worked for me:

  $("#example_form").validate({ rules: { example_field: { required: { depends: function () { $(this).val($.trim($(this).val())); return true; } } }, }, messages: { example_field: {required: "Custom Validation Message for example_field"}, } }); 
0
Jun 14 '16 at 7:44
source share



All Articles