1
\$\begingroup\$

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?

asked Jul 6, 2013 at 12:29
\$\endgroup\$
1
  • \$\begingroup\$ Seems inflexible, sometimes one needs temporarily invalid objects \$\endgroup\$ Commented Jul 6, 2013 at 14:30

1 Answer 1

2
\$\begingroup\$

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.

answered Jul 9, 2013 at 11:53
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.