Javascript null or empty string does not work - javascript

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 ?

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.

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

You should use
if (!veri.YeniMusteriEkleTextBox) {
This also checks for undefined which is not the same as null

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

Related

Way to test empty length property for null and return a string?

I am working through a challenge and trying to set it up so in the event that you pass a string you can determine if there are between 2 and 4 of the letter argument in that string.
My testing of the function worked, however if the matched array is 0 length (in the event there are no matching letters in said string) there is no way to measure the length. I get the error : TypeError: Cannot read property 'length' of null
I tried using a conditional that would return a string if the length was null. Didn't work, I'm not sure if there is a way to funnel this error into a conditional. Any ideas?
TLDR: Is there a way catch to TypeError: Cannot read property 'length' of null before it throws an error?
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex);
if (matched.length == null) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
countLetters('Letter', 'e');
true
countLetters('Letter', 'r');
false
countLetters('Letter', 'z');
//TypeError: Cannot read property 'length' of null
If(matched == null || matched.length != 0)
You can try let matched = string.match(regex) || [];
matched.length == null will always be false, so try matched.length === 0
two changes required to make it work as you need:
handle null when no match is found
check for length appropriately
corrected code below:
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex) || [];
if (matched.length == 0) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
i would strongly advise that you name your method appropriately. it isn't aligned with the return value or it's type. also, you return either string or a boolean value. one should refrain from that. return values of the same type irrespective of whether a match is found or otherwise.

Easier way to have RegExp.test() return false for null values?

let regex = /[a-z]+/;
regex.test('a'); // true
regex.test(''); // false
regex.test(null); // true
regex.test(undefined); // true
So based on this link, Is it a bug in Ecmascript - /\S/.test(null) returns true?, it looks like the null value is coerced to a string 'null'. WTF? Why on earth is this designed this way? I also can't find any documentation on this behavior. Is there a way to return false for null/undefined values (without hardcoding in checks for 'null', etc.)?
If you're testing a variable, you could do:
regex.test(var || '')
so that it will default to the empty string if it's not set.
The argument of RegExp.test() is expected to be a string. If it isn't, it is converted to a string:
var regex = /\[object Object\]/;
console.log(regex.test({})); // true
This is standard behavior in JavaScript. E. g. "null".replace(null, {}) === "[object Object]".
Follow Check if a variable is a string to check whether or not the argument is a string:
if (typeof myVar === 'string' || myVar instanceof String) { ... }
else return false;
You can override test method.
old = regex.test
regex.test = function(str){
str = str? str: "";
return old.call(this, str);
}
regex.test(null); // false
One way is to get your expected output is to check the value first and replace it with "" empty string in case of null or undefined
let regex = /[a-z]+/;
function test (inp){
return regex.test(inp? inp: '');
}
test(null); // false
test(undefined); // false

RegExp filter in JavaScript (Angular.js)

I want to custom filter in Angular.js.
In case an object has name == null, and I insert "u" to filter-> it returns obj, which name == null because re.test(null)=true, but others characters are returning false. Can you tell me why? How can I prevent this case?
You need to check if obj.name is also defined before testing it with regexp:
$scope.searchFilter = function(obj) {
var re = new RegExp($scope.searchText, 'i');
return !$scope.searchText || (obj.name && re.test(obj.name)) || re.test(obj.age.toString());
};
Otherwise, null casted to String type yields "null" and it's matched of course.
Demo: http://jsfiddle.net/26fZb/232/

Determining string length in Node JS when string may be null

I'm trying to learn Node and have the function:
this.logMeIn = function(username,stream) {
if (username === null || username.length() < 1) {
stream.write("Invalid username, please try again:\n\r");
return false;
} else {
....etc
and I'm passing it
if (!client.loggedIn) {
if (client.logMeIn(String(data.match(/\S+/)),stream)) {
I've tried both == and ===, but I'm still getting errors as the username is not detecting that it is null, and username.length() fails on:
if (username === null || username.length() < 1) {
^
TypeError: Property 'length' of object null is not a function
I'm sure that Node won't evaluate the second part of the || in the if statement when the first part is true - but I fail to understand why the first part of the if statement is evaluating to false when username is a null object. Can someone help me understand what I've done wrong?
length is an attribute, not a function. Try username.length
You're passing String(data.match(/\S+/)) as username argument, so when data.match(/\S+/) is null, you get "null" not null for username, as:
String(null) === "null"
So you need to change your condition:
if( username === null || username === "null" || username.length < 1 )
If you require a non-empty string, you can do a simple "truthy" check that will work for null, undefined, '', etc:
if (username) { ... }
With that approach, you don't even need the .length check. Also, length is a property, not a method.
Edit: You have some funkiness going on. I think you need to start with how you're passing in your username - I don't think that your String(data.match(/\S+/)) logic is behaving the way that you're expecting it to (credit to #Engineer for spotting this).
Your match expression is going to return one or two types of values: null or an Array. In the case that it's null, as #Engineer pointed out, you end up passing in "null" as a string, which should resultantly pass your username check later on. You should consider revising this to:
if (!client.loggedIn) {
var matches = data.match(/\S+/);
if (client.logMeIn(matches ? matches[0] : '',stream)) {
Regarding .length being equal to 1 in all cases - that doesn't honestly make a lot of sense. I would recommend adding a lot of console.log() statements to try and figure out what's going on.
Try
if( username === null || username.toString().length < 1 )
I used if( username === null || username.length < 1 ) and it failed at length check.

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}

Categories

Resources