2013-05-18 71 views
0

我剛剛開始使用JavaScript並希望驗證表單。我發現的所有教程都會爲反饋創建一個警報,但我想使用onblur並在該字段旁邊顯示一條錯誤消息。我設法分開執行這兩個功能,但不能合併它們。我真的很感謝你的幫助!函數內部的javascript函數

這是我想出了,但它並沒有做什麼,我需要:

function validateFirstName() 
    { 
    var x=document.forms["demo"]["firstname"].value; 
    if (x==null || x=="" || x==) 
     { 
     function addMessage(id, text) 
     { 
       var textNode = document.createTextNode(text); 
       var element = document.getElementById(id); 
       element.appendChild(textNode); 
       document.getElementById('firstname').value= ('Firstname must be filled out') 
      } 

     return false; 
     } 
    } 

回答

0

因此,以下是通過在提交表單時檢查輸入值來驗證表單字段的簡單方法。在這個例子中,錯誤消息只是發送到表單的div元素,但這應該仍然會幫助你。

的HTML代碼看起來是這樣的:

<div id="errors"></div> 
<form onSubmit="return validate(this);"> 
<input type="text" name="firstName" placeholder="What's your first name?"> 
<button type="submit" value="submit">Submit</button> 
</form> 

的JavaScript代碼看起來是這樣的:

function validate(form) { 
var errors =''; 

if(form.firstName.value =="") { 
    errors += '<li>Please enter your first name</li>'; 
} 
if(errors !='') { //Check if there are any errors, if there are, then continue 
    var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message" 
    message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML 
    return false; 
} else { 
    return true; 
} 
} 

一旦你明白了這一點,你應該能夠推測休息了你自己或者轉到http://www.w3schools.com/並查看javascript部分以幫助您。

0

我不知道你真正想要的。如果我理解正確的(我可以非常錯誤的)你正在尋找的東西,如:

var x = undefined; // Can be undefined, null, or empty string 
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined 
    function addMessage(id, text) { 
     // Your validation code goes here 
     alert(id + text); 
    }; 
    addMessage(1234, "Mandatory field!"); 
} 

注意,有幾種方法可以做到這一點。我只是展示了我能想到的最簡單的方法...