Himavanth
Himavanth

Reputation: 410

Javascript string validation issue

I'm using the below function to do string validation:

isValidString = value => (value && value.trim() !== '');

I'm expecting a boolean return, but when value = '' return value is an empty string.

Can someone please explain why this is happening?

Upvotes: 1

Views: 232

Answers (3)

PicTools
PicTools

Reputation: 49

You could check if value is undefined using typeof value ! = 'undefined'

isValidString = value => typeof value != 'undefined' && value.trim() !== '';

Upvotes: 0

user9628338
user9628338

Reputation:

Strings with length 0 are evaluated as false in Boolean expressions in JavaScript, and since you are using the short circuit Boolean AND operator which stops further evaluation when it encounters a false value. Hence your expression returns an empty string as it caused your expression to evaluate to false.

Upvotes: 0

Anoop
Anoop

Reputation: 23208

Try this.

&& operator don't assign Boolean values but return value of last executed expression. for example in above method if you pass empty string then it return value as empty string equivalent to false. and if you pass non empty string then second part will return value.trim() !== '' which is either true of false.

    isValidString = value => !!(value && value.trim() !== '');
    console.log(isValidString(""))
    console.log(isValidString("a"))

Upvotes: 2

Related Questions