Search code examples
javascriptobjecttestingerror-handlinginline

How to handle errors for inline functions inside an object


At the moment I've got this:

const checkText = (t) => ({
    isNotEmpty: function () {
      if (t.length === 0) {
        throw new Error("isNotEmpty false");
      }
      return this;
    },
    isEmail: function () {
      const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,20})+$/;
      if (!emailRegex.test(t)) {
        throw new Error("isEmail false");
      }
      return this;
    }
};

Using a try catch, if the text is not valid, an error is thrown and handled this way:

const isFieldValid = (email) => {
  try {
    const v = checkText(email)
      .isNotEmpty()
      .isEmail();
    if (v) {
      return true;
    }
  } catch (error) {
    return false;
  }
};

The goal is to short and clean the code, to avoiding the try catch, to have the final call in one line like this:

const isFieldValid = checkText('valid text').isNotEmpty().isEmail(); // one line

PS: I know there are library out there for validation. The code is an example.


Solution

  • class CheckText {
      constructor(t) {
        this.t = t;
        this.valid = true;
      }
      isNotEmpty() {
        this.valid &&= this.t.length>0;
        return this;
      }
      isEmail() {
        this.valid &&= CheckText.emailRegex.test(this.t);
        return this;
      }
      static emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,20})+$/;
    }
    
    const isFieldValid = new CheckText('test@example.com').isNotEmpty().isEmail().valid;
    console.log(isFieldValid);

    However, I'd prefer to do it like this:

    const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,20})+$/;
    const isNotEmpty = t => t.length>0;
    const isEmail = t => emailRegex.test(t);
    const validate = (t, validators) => validators.every(v=>v(t));
    console.log(validate('test@example.com', [isNotEmpty, isEmail]));
    console.log(validate('testexample.com',  [isNotEmpty, isEmail]));
    console.log(validate('',                 [isNotEmpty, isEmail]));