0

So i have a pretty basic account registration form. Submitting the form works fine, so does the validation of the input fields. What doesn't work, is preventing the submit when an input is not correct.

<form id="register">
    <input id="username" name="username" minlength="3">
    <input id="activate" type="button" value="activate">
</form>

<script>
$().ready(function(){
    $("#register").validate({
        rules: { username: "required" },
        messages: { username: "Please enter a Username }
    });
});

$("#activate").click(function(){
    var username = $("#username").val();

    $.ajax({
        type: "POST",
        url: "validateuser.php",
        data: { username: username }
    }).done(function(data){
    console.log(data);
    });
});
</script>

So this is a simplified example of my code. I know that it can't work like it is right now, since the .click function has nothing to do with the validate(). But I just can't figure out how to "combine" the two functions. validate.js does change the classes of the inputs to valid/invalid tho, so i could potentially check in my $.ajaxfunction for that. But there has to be a more elegant solution.

I always get very confused when i use library's because i dont know how they interact with "regular" jQuery. Also worth mentioning that I'm fairly new to jQuery and just starting to get the hang of it.

I really appreciate any input on this matter.

K DB
  • 3
  • 4

1 Answers1

0

Use submit handler. Because you are initiating ajax on click on the activate button which is a separate function than the validation function. So it will be called bypassing/ignoring the validation errors. So use submitHandler inside jquery validation function.

<script>
$().ready(function(){
    $("#register").validate({
        rules: { username: "required" },
        messages: { username: "Please enter a Username },
        submitHandler:function(){    // Use submitHandler
            var username = $("#username").val();

            $.ajax({
            type: "POST",
            url: "validateuser.php",
            data: { username: username }
                    }).done(function(data){
                    console.log(data);
                });
            }
    });
});

</script>
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
  • Thanks for the quick answer. Yes I didn't know how to implement the submitHandler. This seems to be the solution. But the button just doesnt do anything now. I think it has to do with the `` not beeing "submit", right? – K DB Sep 29 '17 at 09:30
  • 1
    Yes, setting the `` to `submit` worked. Thanks a lot. – K DB Sep 29 '17 at 09:33