2013-05-18 10 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 요소로 보내지 만 여전히 도움이됩니다.

<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> 

자바 스크립트 코드는 다음과 같은 : : 당신이 이것을 이해하면

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

것은 당신이 당신의 자신에 나머지를 파악 할 수 있어야한다

HTML 코드는 다음과 같이 보입니다 또는 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!"); 
} 

참고 : 몇 가지 방법이 있습니다. 그냥 생각해 볼 수있는 가장 간단한 방법을 보여줍니다.

관련 문제