RayBan RayBan - 4 months ago 5
HTML Question

Why does this simple E-Mail validation not excute?

I wrote this simple form validation script for the school, but the function which checks the E-Mail, called "absender()", doesn't work, and I don't get why. The other two functions, which are validating the names do work. I literally trying for days and hours now, any help is much appreciated.



window.onload = function() {
'use:strict';

var nachName = document.getElementById('Nachname');
nachName.addEventListener('blur', nName);

var vorName = document.getElementById('Vorname');
vorName.addEventListener('blur', vName);

var absender = document.getElementById('Absender');
absender.addEventListener('blur', absender);

function nName() {
var re = /^[A-Za-z]+$/;

if (re.test(document.Formular.Nachname.value)) {
document.getElementById("formuText").innerHTML = "";
} else {
document.getElementById("formuText").innerHTML = "Fehlerhafte Eingabe!";
}
}

function vName() {
var re = /^[A-Za-z]+$/;

if (re.test(document.Formular.Vorname.value)) {
document.getElementById("formuText").innerHTML = "";
} else {
document.getElementById("formuText").innerHTML = "Fehlerhafte Eingabe!";
}
}

function absender() {
var at = /\S+@\S+\.\S+/;

if (at.test(document.Formular.Absender.value)) {
document.getElementById("formuText").innerHTML = "";
} else {
document.getElementById("formuText").innerHTML = "Fehlerhafte Eingabe!";
}
}
}

<form name="Formular">
<p id="formuText"></p>
<fieldset name="fieldset">
<legend>Persönliche Daten</legend>
<p id="formText"></p>
<label for="Nachname">Nachname</label>
<input type="text" id="Nachname" placeholder="Mustermann" name="Nachname">
<label for="Vorname">Vorname</label>
<input type="text" id="Vorname" placeholder="Max" name="Vorname">
<label for="absender">E-Mail:</label>
<input type="text" id="Absender" name="Absender" placeholder="MaxMuster@Mann.de">
</fieldset>
</form>




Answer

Your element variable and validation function have the same name.

...
var absender = document.getElementById('Absender'); // <-- this variable
absender.addEventListener('blur', absender);
...
function absender() {                             // <-- has the same name of this function
  var at = /\S+@\S+\.\S+/;
...

They can't have the same name. Roughly, they "occupy the same namespace".

To fix, rename either the function or the element:

var absenderElement = document.getElementById('Absender'); // notice the variable rename
absenderElement.addEventListener('blur', absender);

In the example above, the variable was renamed from absender to absenderElement, so the function can keep the name absender().