Filip Nilsson
Filip Nilsson

Reputation: 407

Validate textfield and add warning-text right to textbox

I'm trying to add a warning-text right to my textfield when the name is not valid. I have the code for the validation but i can't make some text appear when it input is invalid.

HTML-code:

<label for="fname">Firstname:</label> 
<input type="text" name="Firstname:" id="fname" size="40" />

Javascript-code:

fname.onchange = function() {
    var fn = /^[a-z\s]{2,30}$/i;
    if(!(fn.test(fname.value))) {
        //Insert text right to the textbox here!

    }
}

Upvotes: 2

Views: 6078

Answers (2)

Filip Nilsson
Filip Nilsson

Reputation: 407

Thank you, i just cant get the star in the right position, now it's in the end of the whole form, not after the individual inputfield.

Also, i can't get rid of the star when the field is validated.

Javascriptcode:

fnamn.onchange = function() {
            var fn = /^[a-zåäö\s]{2,30}$/i;
            if(!(fn.test(fnamn.value))) {
                var warningDiv = document.createElement("div");
                warningDiv.className = "star";

                var Astar = "*";
                var star = document.createTextNode(Astar);
                warningDiv.appendChild(star);

                fnamn.parentNode.insertBefore(warningDiv, this.fnamn);

            } else {
                var next = this.nextSibling;
                if (next && next.className === "star")
                this.parentNode.removeChild(next);
            }
        }

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83358

DEMO

You can create a span to hold the text you want to display, then insert it after the textbox. You do this by inserting the new span before the textbox's nextSibling

this.parentNode.insertBefore(warningSpan, this.nextSibling);

And if there is no nextSibling, then insertBefore will be smart enough to insert it after the textbox:

Full code:

var fname  = document.getElementById("fname");
fname.onchange = function() {
    var fn = /^[a-z\s]{2,30}$/i;
    if(!(fn.test(fname.value))) {
        //Insert text right to the textbox here!

        var warningSpan = document.createElement("span");
        warningSpan.className = "redTextClass";
        warningSpan.innerHTML = "Please enter a value";
        this.parentNode.insertBefore(warningSpan, this.nextSibling);
    } else {
        //no validation error, so we better remove it:
        var next = this.nextSibling;
        if (next && next.className === "redTextClass")
           this.parentNode.removeChild(next);
    }
}

Upvotes: 3

Related Questions