if not valid delete the object
Don't. Better, test the email address to be valid before trying to create the user.
or return nothing
You can't really. Returning nothing from a constructor is effectively quite impossible, except you throw an exception.
Use an extra factory function instead:
function isValidEmail(str) {
// http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/
return /.+@.+\..+/.test(str);
}
function User(email) {
// possible, but better don't do this:
// if (!isValidEmail(email)) throw new Error("Tried to create User with invalid email")
this.email = email;
}
User.prototype.checkValid = function () {
return isValidEmail(this.email);
};
User.create = function(email) {
if (isValidEmail(email))
return new User(email);
else
return null;
};
var user1 = User.create("bob123@aol.com")
if (user1)
this.checkValid() // true