Reputation: 95
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 ?
Upvotes: 1
Views: 22870
Reputation: 178413
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!!!");
}
Upvotes: -1
Reputation: 340045
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!!!");
}
Upvotes: 2
Reputation: 49612
You should use
if (!veri.YeniMusteriEkleTextBox) {
This also checks for undefined
which is not the same as null
Upvotes: 1
Reputation: 4278
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.
Upvotes: 4