jQuery .valid() not working? (Validation Plugin)

689 views Asked by At

I'm using jQuery Validation Plugin and my code is not working as intended. What I want is when I click the submit button the program will check if the form is properly filled out and contains a url and then runs a function. In this case it always alert('true).

$(document).ready(function(){
    $('#button1').submit(function() {
        if($("#button1").valid()){
            alert('true');
        }
        else{
            alert('false');
        }
    });
});

Not sure if this is relevant but I'm using Flask and WTForms:

Form:

class SVN_Path(Form):
    svn_url1=StringField('SVN Directory:',[validators.URL()])
    svn_url2=StringField('SVN Directory:',[validators.URL()])

Html:

<form id="button1" action="{{ url_for('test4') }}"method="post" name="SVNPATHS">
    {{form1.hidden_tag()}}
    <br>
    <div class="svninput" id="input1">
        {{ form1.svn_url1.label }}
        {{ form1.svn_url1 }}
    </div>
    <input id="update" class="button" type="submit" name="updatepaths" value="Update">
    <div class="svninput" id="input2">
        {{ form1.svn_url2.label }}
        {{ form1.svn_url2 }}
    </div>
</form>

UPDATE

    $('#button1').submit(function(){
        var is_valid = $(this).validate({
            rules: {
                svn_url1: {
                    required: true,
                    url: true
                },
                svn_url2: {
                    required: true,
                    url: true
                }
            }
        });
        if(is_valid){
            alert('true');
        }
        else{
            alert('false');
        }
    });
});

I tried what dirn had suggested but this still gives back true even if both fields are empty.

2

There are 2 answers

4
depperm On

You could try it this way:

var form = $( "#button1" );
form.validate();
$( "#update" ).click(function() {
  alert( "Valid: " + form.valid() );
});

This will validate the form when the button is clicked, instead of when the form is clicked.

1
dirn On

You haven't set up any validation rules. The plugin sees both fields as optional strings. You can go about changing this in a couple of ways.

<input type="url" name="svn_url1" required>

(Note that you sometimes refer to it as svn_url1 and sometimes as svn_url1s.)

The easiest way to accomplish this is with WTForm's URLField

from wtforms.fields.html5 import URLField
from wtforms.validators import wtforms.validators.DataRequired

class SVNPath(Form):
    svn_url1 = URLField(validators=[wtforms.validators.DataRequired()])

The other way to do this is to use the validate method for the form object and pass the validation rules to it.

$('#button1').submit(function() {
  var is_valid = $(this).validate({
      rules: {
        svn_url1: {
          required: true,
          url: true
        }
      }
    });
});