javascript建立通用表單驗證代碼

來源:互聯網
上載者:User
首先看下效果,沒什麼特別,呵呵!
調用的代碼呢,則是相當簡單,不需要建立其他的Label或者span標籤,指令碼將自動產生:
<input type="text" id="txt1" onkeyup="checkResult(this.value == '', 'txt1', ' *這裡不可為空喔!')" />
  接下來我們看下這個checkResult這個函數,checkCondition參數表示判斷條件,當條件為true時顯示提示資訊;showAfterId參數為建立的顯示提示資訊的標籤之前的元素ID,在這裡我們在input後面建立一個span來顯示提示資訊,因而 傳入的參數值為當前input的ID“txt1”;最後一個參數為顯示的文字,這個就不用??鋁恕?/div>
View Code
//驗證不可為空展示提示資訊
function checkResult(checkCondition, showAfterId, showMsg) {
var showLabelId = showAfterId + "showMsg";
if (checkCondition) {
if (document.getElementById(showLabelId)) {
document.getElementById(showLabelId).innerHTML = showMsg;
} else {
createShowElement(showAfterId, showLabelId, "color:red", showMsg, 'span');
}
} else if (!checkCondition) {
if (document.getElementById(showLabelId))
document.getElementById(showLabelId).innerHTML = '';
}
}
 好,最後我們來看這個“createShowElement(currentId, elementId, style, showMsg, tagName)”函數:currentId即當前標籤的ID;elementId為建立的標籤的ID;style為建立的標籤的樣式,按照樣式的寫法即可;showMsg不講了;tagName為建立的標籤名,如label或者span等。
View Code
//建立展示提示資訊的dom
function createShowElement(currentId, elementId, style, showMsg, tagName) {
if (!tagName) tagName = 'label';
var currentDom = document.getElementById(currentId);
var showMsgDom = document.createElement(tagName);
//showMsgDom.setAttribute("style", "color:" + textColor + ";");
if (style)
showMsgDom.setAttribute("style", style);
showMsgDom.setAttribute("id", elementId);
showMsgDom.innerHTML = showMsg;
currentDom.parentNode.insertBefore(showMsgDom, currentDom.nextSibling);
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.