Skip to main content

How to validate empty space in textbox in Javascript

Sometimes we have to validate the input value with blank/empty spaces in javascript. You can validate empty space in textbox in javascript using regex and can also use jQuery $.trim() method.

  • Validation for empty spaces in javascript using regex

    function hasBlankSpaces(str){
        return  str.match(/^\s+$/) !== null;
    }
    var addr = ' ';
    if(hasBlankSpaces(addr)){
      console.log('The variable has blank spaces');
    }

    Output:

    The variable has blank spaces

    This code snippet will help you to find out the variable has blank spaces or not.

  • Validate variable if value of variable is null, empty and has blank spaces in javascript

    function isNullEmptyBlank(str){
        return str === null || str.match(/^ *$/) !== null;
    }
    
    var addr = '';
    
    if(isNullEmptyBlank(addr)){
      console.log('The value of variable is null, empty or has blank spaces');
    }

    Output:

    The value of variable is null, empty or has blank spaces

    This code snippet will validate input variable if value of variable is null (null), empty ('') and has blank spaces(' ').

     

     

  • Back to code snippet queries related javascript