Form validation using Jquery validate

Asked

Viewed 685 times

1

I’m here with a problem validating my form, every time I change the country I reload the page:

<select class="form-control" id="pais" name="pais" 
        onchange="document.getElementById('form_user').action='';this.form.submit();">

I do this to add new fields if the country is Portugal.

The problem is I’m using the validate Jquery and the validation of this and other fields disappears when changing the country, because I reload the page.

How can I keep the validation fields always working, from the moment I click for once on the button of Submit?

How I do the validation:

$('#form_user').validate({
        rules: {
            nome: {
                minlength: 3,
                maxlength: 50,
                required: true
            },
            //outros campos...
            pais: {
                valueNotEquals: "0"
            }
       }
       //mensagens, etc...
 });
  • 1

    It would not be the case to use ajax to get the list of countries?

  • What for? My validation is whether or not you selected a country.

  • Oh yes, I got the question wrong. I thought you were reloading the page to get the list of states and municipalities, for example.

1 answer

1


The way I found to solve the problem was to check, in PHP, whether a POST, if yes I do a validation.

So I get the assurance that every time there is POST the validation shall be carried out.

My script:

var validator = $('#form_user').validate({
    rules: {
        nome: {
            minlength: 3,
            maxlength: 50,
            required: true
        },
        //outros campos...
        pais: {
            valueNotEquals: "0"
        }
    }
    //mensagens, etc...
});

If there is a POST the validation of the form:

<?php
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
?>
    validator.form();
<?php 
}
?>

In the case of click at the button of submit also does validation.

$( "#submit" ).click(function() 
{
    validator.form();
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.