Angel Politis Angel Politis - 3 months ago 7
HTML Question

Custom error event for object

I'm creating an object to handle my inputs and currently I'm stuck in an attempt to create a custom error event which should trigger whenever a user enters more characters than permitted or other than the characters that are allowed.

I currently have the following code, which produces no error whatsoever, but it also doesn't execute the callback function which, I guess, means that my attempt to trigger the custom event was fruitless.

Code:



/* ----- JavaScript ----- */
function Input (selector) {
var self = this,
element = document.querySelector(selector),
isCorrect = false,
err = new Event("err");

/* Properties */
this.maxLength = 32;
this.acceptedChars = /[\s\S]*/;

/* Methods */
this.onerror = function (callback) {
element.addEventListener('err', function (e) {
if (callback instanceof Function) {
if (!isCorrect) return callback();
}
else throw new Error("Error");
}, false);
element.dispatchEvent(err);
};

element.onkeypress = function () {
return isCorrect = self.acceptedChars.test(String.fromCharCode(e.which)) &&
(self.maxLength > this.value.length);
};
};

/* Creating an instance of Input */
var myInput = new Input("#text");
myInput.maxLength = 4;
myInput.acceptedChars = /[a-z]/;
myInput.onerror(function() {
console.error("There's an error!");
});

<!----- HTML ----->
<input id = "text" type = "text"/>





Any help will be greatly appreciated!

Answer

Use new CustomEvent() to define custom event, call callback

/* ----- JavaScript ----- */
function Input(selector) {
  var self = this,
    element = document.querySelector(selector),
    isCorrect = false,
    // err = new Event("err"),
    // define new `CustomEvent`
    err = new CustomEvent("err", {
      detail: "input error"
    });

  /* Properties */
  this.maxLength = 32;
  this.acceptedChars = /[\s\S]*/;

  /* Methods */
  this.onerror = function(callback) {

    element.addEventListener('err', function(e) {
      if (callback instanceof Function) {
        if (!isCorrect) {
          console.log(e.detail);
          // call `callback()`
          return callback();
        }
      } else throw new Error("Error");
    }, false);
    element.dispatchEvent(err);
  };

  element.onkeypress = function(e) {
    isCorrect = self.acceptedChars.test(String.fromCharCode(e.which)) 
                && (self.maxLength > this.value.length);
    if (!isCorrect) {
      element.dispatchEvent(err);
    }
    return isCorrect
  };
};

/* Creating an instance of Input */
var myInput = new Input("#text");
myInput.maxLength = 4;
myInput.acceptedChars = /[a-z]/;
myInput.onerror(function() {
  console.error("There's an error!");
});
<!----- HTML ----->
<input id="text" type="text" />

Comments