What javascript method can you use to send a form for validation prior to submitting it?

I would really appreciate anyone's help with this as I just can't seem to get it working. I am using a javascript code to check my form before it is submitted. I check for things like empty boxes.

If boxes are empty then this should display one of three divs which contains a standard error text.

"There was an error"

I have three different divs, div1 div2 and div3 which contain error statements. I have done this because I have divided my form into three sections. Therefore I want my javascript to perform three different checks on the three different sections in my form and if an error has occurred in which ever section then display div1 or div 2 or div3 for that section.

Section 1 
<div 1>
<input = firstname>
<input = lastname>
<input = email>
<input = email2>

section 2
<div 2>
<input = contactnum>
<input = mobnum>
<input = postcode>

section 3
<div 3>
<input = compname>
<input = compreg>

here is my javascript code I am trying to put together but it's not working, it submits the form without doing any checks. please can someone show me where I am going wrong.

<script>
    function validateForm() {
        var a = document.forms["register"]["firstname"].value;
        var b = document.forms["register"]["lastname"].value;
        var c = document.forms["register"]["email"].value;
        var d = document.forms["register"]["email2"].value;
        if (a == null || a == "" || b == null || b == "" || c == null || c == ""|| d == null || d == "") {
            $(".form_error").show();
            $('html,body').animate({
               scrollTop: $(".form_error").offset().top - 180 
            });


            var e = document.forms["register"]["contactnum"].value;
            var f = document.forms["register"]["mobnum"].value;
            var g = document.forms["register"]["postcode"].value;
            if (e == null || e == "" || f == null || f == "" || g == null || g == "") {
                $(".form_error").show();
                $('html,body').animate({
                     scrollTop: $(".form_error").offset().top - 180 
                });


                var h = document.forms["register"]["compname"].value;
                var i = document.forms["register"]["compreg"].value;
                if (h == null || h == "" || i == null || i == "") {
                    $(".form_error").show();
                    $('html,body').animate({
                        scrollTop: $(".form_error").offset().top - 180 
                    });

                    return false;
                }   
            }
        }
    }
 </script>

Path // www.yourhtmlsource.com → JavaScript → FORM VALIDATION


One of the primary reasons JavaScript was assembled was to check whether the values entered into forms by readers were correct, thereby bypassing the lengthy trip to a CGI program to do the check. Here we'll learn the methods used to validate form input, using the onSubmit event handler.

Page Navigation:
Validating Form Input · Implementing the Check | Accessing Values · Text Boxes, <textarea>s and hiddens · Select Boxes · Check Boxes · Radio Buttons

What javascript method can you use to send a form for validation prior to submitting it?
This page was last updated on 2012-08-21



Validating Form Input

When you submit a form to a CGI program that resides on the server, it is usually programmed to do its own check for errors. If it finds any it sends the page back to the reader who then has to re-enter some data, before submitting again. A JavaScript check is useful because it stops the form from being submitted if there is a problem, saving lots of time for your readers.

The CGI script is still more reliable, as it always works regardless of whether JavaScript is enabled on the client-side or not; but having this extra safety barrier is a nice thing to have in place. It makes your page much more user-friendly, and takes out the frustration of having to fill out the same form repeatedly. It's also very precise, as you can point out the exact field where there's a problem.

Implementing the Check

We're going to be checking the form using a function, which will be activated by the form's submit event — therefore, using the onSubmit handler. Add an attribute like this to the form you wish to validate:

<form action="script.cgi" onSubmit="return checkform()">

Where checkForm is the name of the function we're about to create. If you've learnt your functions properly, you should be able to guess that our function will return a Boolean value — either true or false. Submit's default action is to submit the data, but if you give onSubmit a value of return false, it will not be submitted; just like how we can stop a link from being followed. Of course, if there are no problems, the function call will be replaced by true and the data will be submitted. Simple...

It's impossible for me to give you a definitive validation script, as every form is different, with a different structure and different values to check for. That said, it is possible to give you the basic layout of a script, which you can then customise to the needs of your form.

A general script looks like this:

function checkform()
{
	if (value of first field is or isn't something)
	{
		// something is wrong
		alert('There is a problem with the first field');
		return false;
	}
	else if (value of next field is or isn't something)
	{
		// something else is wrong
		alert('There is a problem with...');
		return false;
	}
	// If the script gets this far through all of your fields
	// without problems, it's ok and you can submit the form

	return true;
}

If your form is quite complex your script will grow proportionally longer too, but the fundamentals will stay the same in every instance — you go through each field with if and else statements, checking the inputted values to make sure they're not blank. As each field passes the test your script moves down to the next.

If there is a problem with a field, the script will return false at that point and stop working, never reaching the final return true command unless there are no problems at all. You should of course tailor the error messages to point out which field has the problem, and maybe offering solutions to common mistakes.

Accessing Values

Having read the Objects and Properties page, you should now know how to find out the values of form elements through the DOM. We're going to be using the name notation instead of using numbered indexes to access the elements, so that you are free to move around the fields on your page without having to rewrite parts of your script every time. A sample, and simple, form may look like this:

<form name="feedback" action="script.cgi" method="post" onSubmit="return checkform()">
<input type="text" name="name">
<input type="text" name="email">
<textarea name="comments"></textarea>
</form>

Validating this form would be considerably simpler than one containing radio buttons or select boxes, but any form element can be accessed. Below are the ways to get the value from all types of form elements. In all cases, the form is called feedback and the element is called field.

Text Boxes, <textarea>s and hiddens

These are the easiest elements to access. The code is simply

document.feedback.field.value

You'll usually be checking if this value is empty, i.e.

if (document.feedback.field.value == '') {
	return false;
}

That's checking the value's equality with a null String (two single quotes with nothing between them). When you are asking a reader for their email address, you can use a simple » address validation function to make sure the address has a valid structure.

Select Boxes

Select boxes are a little trickier. Each option in a drop-down box is indexed in the array options[], starting as always with 0. You then get the value of the element at this index. It's like this:

document.feedback.field.options
[document.feedback.field.selectedIndex].value

You can also change the selected index through JavaScript. To set it to the first option, execute this:

document.feedback.field.selectedIndex = 0;

Check Boxes

Checkboxes behave differently to other elements — their value is always on. Instead, you have to check if their Boolean checked value is true or, in this case, false.

if (!document.feedback.field.checked) {
	// box is not checked
	return false;
}

Naturally, to check a box, do this

document.feedback.field.checked = true;

Radio Buttons

Annoyingly, there is no simple way to check which radio button out of a group is selected — you have to check through each element, linked with Boolean AND operators . Usually you'll just want to check if none of them have been selected, as in this example:

if (!document.feedback.field[0].checked &&
!document.feedback.field[1].checked &&
!document.feedback.field[2].checked) {
	// no radio button is selected
	return false;
}

You can check a radio button in the same way as a checkbox.

How do I validate a form before submitting?

How it works:.
First, call each individual function to validate username, email, password, and confirm password fields..
Second, use the && operator to determine if the form is valid. The form is valid only if all fields are valid..
Finally, submit data to the server if the form is valid specified the isFormValid flag..

How JavaScript form can be validated?

Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value.

Which method is used to submit forms in JavaScript?

The formmethod attribute defines the HTTP method for sending form-data to the action URL. The formmethod attribute overrides the method attribute of the <form> element. The formmethod attribute is only used for buttons with type="submit".

Can I use JavaScript to submit a form?

Generally, a form is submitted when the user presses a submit button. However, sometimes, you may need to submit the form programmatically using JavaScript. JavaScript provides the form object that contains the submit() method. Use the 'id' of the form to get the form object.