PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to handle errors for inline functions inside an object

 November 14, 2022     error-handling, inline, javascript, object, testing     No comments   

Issue

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



Answered By - Andrew Parks
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing