user3572583
user3572583

Reputation: 41

Why validation is not working properly in JavaScript?

I am having an input field and a submit button:

        <form action="" method="post">
           <input type="text" name="sponsar_name" id="sponsar_name" />
          <input type="submit" value="Submit"  class="btn-submit" name="submit" onClick="validate()" >
    </form>

      function validate()
    {
        var flag = 0;
    if(document.getElementById("sponsar_name").value == null || document.getElementById("sponsar_name").value == "")
        {
            document.getElementById("sponsar_name").style.borderColor = 'red';
            flag = 1;
            }
            else
            {
                        document.getElementById("sponsar_name").style.borderColor = '';
                }

                if(flag==1)
                {
                    return false;
                }
                else
                {
                    return true;
                }

    }
                     </script>

I have applied a function onClick on submit button .this I have applied for validation.

When I click on submit button it shows red background of textbox but refreshes the page immediately.

If the textbox is blank it should not refresh the page, but in my code it is doing so.

Can anyone help me?

Upvotes: 0

Views: 60

Answers (4)

chandu
chandu

Reputation: 2276

Change you form like this: remove onClik function and add the onSubmit on form header

<form action="" method="post" onsubmit="return validate()">
           <input type="text" name="sponsar_name" id="sponsar_name" />
          <input type="submit" value="Submit"  class="btn-submit" name="submit"/> 
    </form>

Upvotes: 0

gprathour
gprathour

Reputation: 15333

You need to do it this way,

<input type="submit" value="Submit" class="btn-submit" name="submit" onClick="return validate()" >

And when you will return false in your method, your form won't be submitted.

Upvotes: 0

Anuraj
Anuraj

Reputation: 19618

You need to use either onClick="return validate()" or onSubmit="return validate()". It will fix the problem.

using onClick="return validate()"

<form action="" method="post">
    <input type="text" name="sponsar_name" id="sponsar_name" />
    <input type="submit" value="Submit"  class="btn-submit" name="submit" onClick="return validate()" >
</form>

using onSubmit="return validate()"

<form action="" method="post" onSubmit="return validate()">
    <input type="text" name="sponsar_name" id="sponsar_name" />
    <input type="submit" value="Submit"  class="btn-submit" name="submit">
</form>

Upvotes: 0

Laukik Patel
Laukik Patel

Reputation: 743

Try with

<form action="" method="post">
   <input type="text" name="sponsar_name" id="sponsar_name" />
   <input type="submit" value="Submit"  class="btn-submit" name="submit" onClick="return validate()" >
</form>

Upvotes: 1

Related Questions