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);

catch(err) {

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

  • \$\begingroup\$ Seems inflexible, sometimes one needs temporarily invalid objects \$\endgroup\$
    – Esailija
    Jul 6 '13 at 14:30

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() ) {

Also you can create some validation function like

    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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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