0

I want to print out a series of error messages on my html page based on what the user enters such as password, user name, address etc., which the information failed to validate.

My code looks like this:

 function validate(){ var x,y,z; x = document.getElementById("name").value; if (x.length<6){ text="user name too short"; } else { text="validated"; } document.getElementById("aka").innerHTML = text; } 

Now I can only validate one input. In this case the input with id "name".
I want to validate all the inputs like password also in this function.

How could I implement that in the function?

I tried adding more if statement followed by another document.getElementById("aka").innerHTML = text, but didnt work and the first didn't print out.

1
  • Whip something up something on jsfiddle so we have a working example. We're developers, not magicians! Commented Aug 9, 2016 at 14:33

2 Answers 2

1

Create a variable and put all the error messages there. Once you have finished, put the value of that variable in the innerHTML of the element you want.

function validate(){ var x, errors = ""; x = document.getElementById("name").value; if (x.length<6){ errors += "user name too short<br />"; } x = document.getElementById("password").value; if (x.length<6){ errors += "password too short<br />"; } document.getElementById("aka").innerHTML = errors; } 
Sign up to request clarification or add additional context in comments.

Comments

0

You can either store all messages inside text variable

var text = ""; if (x.length<6){ text+="user name too short"; } if(y.lenght<6) { text+= 'pwd too short'; } document.getElementById("aka").innerHTML = text; 

Other option would be using DOM functions as follows:

document.appendChild(document.createTextNode(text)); 

var text =""; text += "user name too short"; text += "<br/>pwd too short"; document.getElementById('out1').innerHTML=text; document.getElementById('out2').appendChild(document.createTextNode('user name too short')); document.getElementById('out2').appendChild(document.createTextNode('pwd too short'));
<div id="out1"></div> <div id="out2"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.