Adrian
Adrian

Reputation: 2291

How to detect in javascript if a field is on focus and clear the error besides it?

I have the function

function validateEmailp() {
var two = document.getElementById('email').value;
var first = two.split("@")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) != -1) {
    document.getElementById("email").value = ""; 
    document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails' 
    return false;
    }   
 return true;
}

HTML is

<input id="email" onblur="validateEmailp()"><div id="emailerrorz"></div>

After the user types in the input field a free e-mail he will get that error (we do not..) But after he rectify the email to a non-free e-mail the error should clear up. How do i do that with javascript?

Upvotes: 0

Views: 60

Answers (2)

davidkonrad
davidkonrad

Reputation: 85528

function validateEmailp() {
    var two = document.getElementById('email').value;
    var first = two.split("@")[1];
    var badEmails = ["gmail.com", "yahoo.com"]
    if (badEmails.indexOf(first) > -1) {
        document.getElementById("email").value = ""; 
        document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails' 
        return false;
    } 
    document.getElementById('emailerrorz').innerText = '' 
    return true;
}

Upvotes: 1

Halcyon
Halcyon

Reputation: 57719

Make an else case:

if (badEmails.indexOf(first) != -1) {
    document.getElementById("email").value = ""; 
    document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails' 
    return false;
} else {
    document.getElementById('emailerrorz').innerText = ""; // clear error
}

Upvotes: 1

Related Questions