Javascript null or empty string does not work

2019-06-08 03:15发布

问题:

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 ?

回答1:

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.



回答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!!!");
}


回答3:

You should use

if (!veri.YeniMusteriEkleTextBox) {

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



回答4:

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!!!");
}