2013-05-18 67 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!"); 
} 

注意,有几种方法可以做到这一点。我只是展示了我能想到的最简单的方法...