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?
-
\$\begingroup\$ Seems inflexible, sometimes one needs temporarily invalid objects \$\endgroup\$Esailija– Esailija2013年07月06日 14:30:07 +00:00Commented Jul 6, 2013 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.