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

那年仲夏 提交于 2019-12-22 20:18:29

问题


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";
    }

回答1:


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.



来源:https://stackoverflow.com/questions/10293888/how-to-add-errormessages-instead-of-alert-boxes-in-pop-up-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!