top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Submitting Form after validation using javascript

+3 votes
1,907 views

My form is somewhat like this:-

 <form id="form1" method="post" name="form1">
 //...fields like firstname, email......
 <button type="submit" id="submit" name="submit" onclick="validate(this)">SUBMIT</button>
 < /form>

The javascript validate function:-

function validate(ref)
{
    if(document.form1.firstname.value=="")
    {
            window.alert("First Name Cannot be Blank");
            return;
    }

    // validating other fields like email... If any field is invalid return 
    document.form1.action="response"
    document.form1.submit()
} 

Now what the problem is suppose I left the firstname field blank and click submit button then windows alerts that firstname field is mandatory....and as soon as I click the OK button in alert form the form is posted...

Now question is that I assign the action attribute after validating all the fields and if any one is invalid the function returns in which case action attribute of the form is not assigned then how the form is submitted.
The form should have been submitted after all the validation tests will have been successful and controls would have reached document.form1.submit(). And what is the solution for this.

I am using Python Flask and rendering template using jinja2.

posted Apr 2, 2014 by Prakash

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Thank U to both of u...thanks a lot

2 Answers

+1 vote

I hope I understood your problem correctly try onclick="return validate(this);" in place of onclick="validate(this)" make sure you put ;.

Also you need to return false after the alert from JavaScript.

answer Apr 3, 2014 by Salil Agrawal
+1 vote

Use this modified JavaScript code

function validate(ref)
{
    if(document.form1.firstname.value=="")
    {
            alert("First Name Cannot be Blank");
            document.form1.firstname.focus();   //Highlights cursor to that form field
            return false;
    }
   else
   {
    return true;
   }
} 

This code must work.

answer Apr 3, 2014 by Pavan P Naik
Similar Questions
0 votes

Write validation functions and modify the onSubmit event Handler in the form code to validate the following form fields:

  1. Phone Number
    • Must be entered
    • Must be below format
    XXX-XXX-XXXX
    XXX.XXX.XXXX
    XXX XXX XXXX
+1 vote

I want the javascript API which could capture the screen of the client. Does anyone knows about it?

...