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 ?

2
  • 1
    Where is this code located? Inside of a document ready handler? Commented Sep 12, 2013 at 13:03
  • Notice that '' === "" and that checking for .length == 0 was equivalent when you did knew that it was a string Commented Sep 12, 2013 at 13:06

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

You should use

if (!veri.YeniMusteriEkleTextBox) {

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.