Home > Software engineering >  How can we check seperately true/false if empty string [eg: ' '] or string contain only wh
How can we check seperately true/false if empty string [eg: ' '] or string contain only wh

Time:04-01

Hi team Iam new to react and javascript. Iam working on some validation parts. I need to take input only if it is either an empty string or a non empty string but it shouldn't be only white spaces..? how can I check that condition?

var element='' // this should take 
var element='       ' // this shouldnot (bcz contain only empty space) 
var element='Hai how are you'  // this should take
var element='  jji       hooy      ' // this should also take

Can someone help i used trim() but if so it cant identiy '' and ' '

any other solution

CodePudding user response:

You can use a regular expression to match strings that contain only whitespace.

!/^\s $/.test('');    // true
!/^\s $/.test('   '); // false
!/^\s $/.test('Hai how are you');        // true
!/^\s $/.test('  jji       hooy      '); // true
  • ! means ‘not’
  • ^ means ‘start of string’
  • $ means ‘end of string’
  • \s means ‘whitespace, one or more times’

CodePudding user response:

You can validate it like this:

validate(element) {
    return element.length && element.trim().length;
}

CodePudding user response:

You could use the following:

if(str.length && str.trim() === ""){
    return false
  }else{
    return true
  }

CodePudding user response:

If the input value has no length, set the state. If the input value has length, and when you trim it it still has length, set the value. Otherwise don't set the input state.

const { useEffect, useState } = React;

function Example() {

  const [ input, setInput ] = useState('');

  function handleChange(e) {

    // Get the value, and the length of the value
    const { value, value: { length } } = e.target;

    // Check the condition, set the state
    if (!length || (length && value.trim().length !== 0)) {
      setInput(value);
    }
  }

  // Log the updated state
  useEffect(() => console.log(`Current state: ${input}`), [input]);

  return <input onChange={handleChange} />;

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related