kk1076
kk1076

Reputation: 1748

How to add errormessages instead of alert boxes in pop up using javascript

I need to validate the date format in textbox inside popup using JavaScript. Instead of using alert boxes , I need to display the error messages similar to document.getElementById("MainContent_ErrorMsg").innerHTML = "Please Enter valid date".
Is there any other method to achieve this behavior? My JavaScript code is:

    var startdate = document.getElementById("MainContent_uscEventParameters_txtEarliestStartDate");
    var enddate = document.getElementById("MainContent_uscEventParameters_txtLatestEndDate");
    var validformat=/^\d{4}\-\d{2}\-\d{2}$/;
    if (! (startdate.value.match(validformat)) && (enddate.value.match(validforamt)) )
    {
        alert("please enter valid date format");
        //document.getElementById("MainContent_ErrorMsg").innerHTML = "Please enter valid date";
    }

Upvotes: 2

Views: 870

Answers (1)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

Instead of showing alert dialog, you can show the message next to the element using simple and pure JavaScript:

function AddErrorLabel(element, msg) {
    var oLabel = document.createElement("span");
    oLabel.className = "error_msg";
    oLabel.innerHTML = msg;
    var parent = element.parentNode;
    if (element.nextSibling) {
        if (element.nextSibling.className !== "error_msg") {
            parent.insertBefore(oLabel, element.nextSibling);
        }
    }
    else {
        parent.appendChild(oLabel);
    }
}

Usage:

if (! (startdate.value.match(validformat)) && (enddate.value.match(validforamt)) )
{
    AddErrorLabel(startdate, "please enter valid date format");
}

Live test case. (Leave the textbox empty and click submit)

Libraries like jQuery have such features and much better but for simple needs, this should be just enough and it's using basic JavaScript thus cross browser.

Upvotes: 4

Related Questions