Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm looking to create a model in JavaScript. Here is an example of the code that I have so far:

// Person model
function Person(firstName, age) {
    // Check first name
    if (firstName) {
        if (typeof firstName === 'string') {
            this.firstName = firstName;
        } 
        else throw new Error('The first name is not a string.');
    } 
    else throw new Error('First name is a required field.');

    // Check age
    if (age) {
        if (typeof age === 'number') {
            if (age < 0) {
                throw new Error('The age provided is a negative.');
            } 
            else {
                this.age = age;
            }
        } 
        else throw new Error('The age provided is not a number.');
    } 
    else throw new Error('Age is a required field.');
}

// Example usage
try {
    var joel = new Person('Joel', 30);
    console.log(joel);
}    

catch(err) {
    console.log(err.message);
}

Is this an idiomatic approach to the solution? And if so is there a way in which I can improve it?

share|improve this question
    
Seems inflexible, sometimes one needs temporarily invalid objects –  Esailija Jul 6 '13 at 14:30

1 Answer 1

I prefer to create isValid() method instead of exceptions and getValidationErrors() to get array of all errors instead of one error message with exception.

var joel = new Person('Joel', 30);
if( ! joel.isValid() ) {
    console.log(joel.getValidationErrors());
}

Also you can create some validation function like

validate({
    name: {
        type: 'string'
    },
    age: {
        type: 'number',
        minValue: 0,
        maxValue: 150
    }
}, {
    name: firstName,
    age:  age
});

Which will return array of errors. If array length is 0 then validation passed.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.