1

I am trying to test that my string is null or empty, however it does not work.

My Code :

var veri = {
  YeniMusteriEkleTextBox: $('#MyTextbox').val(),
};

if (veri.YeniMusteriEkleTextBox === "" || 
    veri.YeniMusteriEkleTextBox == '' || 
    veri.YeniMusteriEkleTextBox.length == 0 || 
    veri.YeniMusteriEkleTextBox == null) {
  alert("Customer Name can not be empty!!!");
}

How can ı check YeniMusteriEkleTextBox is null or empty ?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
user2706372
  • 95
  • 3
  • 3
  • 10

4 Answers4

4

I would use the ! operator to test if it is empty, undefined etc.

if (!veri.YeniMusteriEkleTextBox) {
    alert("Customer Name can not be empty!!!");
}

Also you do not need the comma after YeniMusteriEkleTextBox: $('#MyTextbox').val(),

Also testing for a length on an object that may be undefined will throw an error as the length will not be 0, it will instead be undefined.

BenM
  • 4,218
  • 2
  • 31
  • 58
2

You need to .trim the value to remove leading and trailing white space:

var veri = {
    YeniMusteriEkleTextBox: $('#YeniMusteriAdiTextbox_I').val().trim()
};

The .trim method doesn't exist on some older browsers, there's a shim to add it at the above MDN link.

You can then just test !veri.YeniMusteriEkleTextBox or alternatively veri.YeniMusteriEkleTextBox.length === 0:

if (!veri.YeniMusteriEkleTextBox) {
    alert("Customer Name can not be empty!!!");
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

You should use

if (!veri.YeniMusteriEkleTextBox) {

This also checks for undefined which is not the same as null

Community
  • 1
  • 1
micha
  • 47,774
  • 16
  • 73
  • 80
  • Additionally OP, if `YeniMusteriEkleTextBox` was `null`, your code would have a runtime exception as `null` does not have the property `length`. When using `null`/`undefined` checks, make sure those occur first as they are (1) the fastest and (2) minimize risk of runtime exceptions as we see here. – Jaime Torres Sep 12 '13 at 13:16
-1

Since no one else is suggestion $.trim, I will

Note I removed the trailing comma too and use the ! not operator which will work for undefined, empty null and also 0, which is not a valid customer name anyway

var veri = {
  YeniMusteriEkleTextBox: $.trim($('#MyTextbox').val())
};

if (!veri.YeniMusteriEkleTextBox) {
  alert("Customer Name can not be empty!!!");
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236