Etcher
Etcher

Reputation: 90

Javascript `typeof` validation issue

I'm starting to learn OOP in JS and I came across this issue where my alert() will not trigger when validateString returns false. I try personOne.setFirstName(''); but the alert() does not trigger.

//define Name class 
function Name () {
    this.firstName = '';
    this.lastName = '';
    this.middleName = '';
    this.details = {
        eyeColor: '',
        hairColor: ''
    }
};

var validateString = function(p) {
    return typeof p != "undefined" && $.trim(p).length;
};

//begin Name methods
Name.prototype.getFullName = function() {
    return this.firstName + ' ' + this.middleName + ' ' + this.lastName;
};
Name.prototype.setFirstName = function(p) {
    if (validateString) {
        this.firstName = p;
    } else {
        alert('Please enter a valid first name.');
    }
};
Name.prototype.setLastName = function(p) {
    if (validateString) {
        this.lastName = p;
    } else {
        alert('Please enter a valid last name.');
    }
};
Name.prototype.setMiddleName = function(p) {
    if (validateString) {
        this.middleName = p;
    } else {
        alert('Please enter a valid middle name.');
    }
};
Name.prototype.setHairColor = function(p) {
    this.details.hairColor = p;
};
Name.prototype.setEyeColor = function(p) {
    this.details.eyeColor = p;
};

//end Name methods

var personOne = new Name();
personOne.setFirstName('John');
personOne.setLastName('Doe');
personOne.setMiddleName('Barry');
personOne.setEyeColor('Brown');
personOne.setHairColor('Black');
document.write(personOne.getFullName());
document.write(personOne.details.eyeColor);
document.write(personOne.details.hairColor);

Upvotes: 0

Views: 157

Answers (2)

KooiInc
KooiInc

Reputation: 123016

You don't need validateString in this case. Consider

Name.prototype.setFirstName = function(p) {
  this.firstName = p || alert('please enter a first name');
}

This is called a short circuit boolean. If no parameter is supplied, or the parameter is an empty string, the alert will be triggered and this.firstName will be undefined. If you need to check te length ofp`, use:

Name.prototype.setFirstName = function(p) {
  this.firstName = (p && p.trim().length) || alert('please enter a first name');
}

Upvotes: 0

David John Welsh
David John Welsh

Reputation: 1569

You need to pass an argument to validateString.

if (validateString(p)) {
  //etc
}

EDIT: ... and also, as @potench mentioned, the reason the if statement was evaluated as true is because this:

if (myFunc) {
  //blah
}

means "if myFunc exists as a defined variable". In this case it's the same as if (3) or if (true).

Upvotes: 2

Related Questions