I am testing email validation with charCode. I am using mousemove, mouseup, or mousedown. So, if the mouse is moved, I try to print the email error validation message under the form box. First I stored the code in a variable and then matched it with a reg expression. Somehow unable to print the error message.
HTML:
<div>
<label>Press the key</label>
</div>
<input type="text" id="kp">
<span id="pr"></span>
<span id="words"></span> <br />
<span id="err"></span>
<button type="button" onClick="pr();">Submit</button>
Javascript:
function pr() {
let k = document.getElementById("kp");
let singlet = k.value;
const emailpatt = /^[a-z0-9] ([_a-z0-9.-] )*[a-z0-9] @[a-z0-9-] (.[a-z0-9-] )*(.[a-z]{2,4})$/;
k.addEventListener("keyup", checkkey, false);
document.getElementById("words").innerHTML = "<br />" singlet " <br />";
let warnT;
let warnE = "Email should be in [email protected] format.\n";
const warnBox = document.getElementById("err");
k.addEventListener("mousemove", checkemail, false);
}
function checkkey(event) {
const charCode = event.charCode;
document.getElementById("pr").innerHTML = singlet;
singlet = singlet;
}
function checkemail(event) {
if (!singlet.match(emailpatt)) {
document.getElementById("err").innerHTML = warnE;
event.preventDefault();
displayWarning(warnE, k, warnT, warnBox);
}
}
function displayWarning(msg, fitem, warningTimeout, warningBox) {
warningBox.innerHTML = msg;
if (document.body.contains(warningBox)) {
clearTimeout(warningTimeout);
} else {
// insert warningBox after firstn
fitem.parentNode.insertBefore(warningBox, fitem.nextSibling);
}
warningTimeout = setTimeout(() => {
warningBox.parentNode.removeChild(warningBox);
warningTimeout = -1;
}, 6000);
}
CodePudding user response:
There are multiple issues with your code but here is a start: when you open the page in Firefox or Chrome and press F12, you’ll see the console pop up which will display Javascript errors. In this case it says “singlet is not defined”. This is because when you define singlet in the pr-function, it has a local scope and cannot be accessed from inside other functions. You can fix this by defining singlet in the global scope, as well as many of the other variables used. You can just remove the function pr() {
and corresponding }
, providing that this code is executed after the HTML has loaded.
Also, you can use <input type="email">
and then the browser will validate the input when the form is submitted.