Question

I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!

This is what I came up with, but it doesn't do what I need:

 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;
      }
  }
Was it helpful?

Solution

So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.

The HTML code looks something like this:

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

The Javascript code looks something like this:

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

Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.

OTHER TIPS

I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:

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!");
}

Note, there are several ways to do it. I just showing the simplest way I can think of...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top