22

I have a HTML5 web application with numerous user-entered fields, and I would like to do some client-side validation on those fields in javascript before sending them to the server. Easy right? Just use JQuery validation plugin --- http://jqueryvalidation.org/

But there's a catch. My web app has no forms. There is no submit anywhere in the HTML. Instead there's a JQuery change handler on every user-changeable element, and when the user changes the value of one of those element, an AJAX call is made. (This nonstandard user interaction architecture makes sense for this application.)

I would like to validate the field before the AJAX call, and use the JQuery validation plugin to do that. But I can't figure out how.

Is it possible to use the JQuery validation plugin without a submit anywhere? How would I do this? Or is another approach better?

Sparky
  • 98,165
  • 25
  • 199
  • 285
David Bridgeland
  • 525
  • 1
  • 9
  • 16

5 Answers5

55

Firstly, and most importantly, you must wrap your input elements inside <form></form> tags for the jQuery Validate plugin to operate. However, a submit button is not required.

Secondly, you can programatically trigger the validity test of any or all elements without a submit button by using the .valid() method.

$(document).ready(function() {

    $('#myform').validate({  // initialize the plugin on your form.
        // rules, options, and/or callback functions
    });

    // trigger validity test of any element using the .valid() method.
    $('#myelement').valid();

    // trigger validity test of the entire form using the .valid() method.
    $('#myform').valid();

    // the .valid() method also returns a boolean...
    if ($('#myform').valid()) {
        // something to do if form is valid
    }

});

DEMO: http://jsfiddle.net/URQGG/

Sparky
  • 98,165
  • 25
  • 199
  • 285
3

You will have to wrap your fields within a form to use the validation plugin and it's a good practice anyway. Also, you can invoke the plugin's validation programmatically and check if the form is valid by doing:

var $form = $('#your_form'),
    validator = $form.validate({...});

//validate the form
validator.form();

//check if the form is valid 
if ($form.valid()) {
    //form is valid
}

For more options, have a look at the docs.

Community
  • 1
  • 1
plalx
  • 42,889
  • 6
  • 74
  • 90
  • 1
    What is the purpose of assigning the object to a variable? An additional line to save a couple characters seems verbose when you can simply call `$('#your_form').validate()` and `$('#your_form').valid()`. (Also, you don't need to call `validator.form()` at all.) – Sparky Aug 13 '13 at 23:54
  • @Sparky, there are several methods that can only be invoked on the validator returned from the `validate` function, so it's a good idea to keep a reference to it if needed. Also, it's a bad practice to always requery the DOM for getting elements referenced multiple times. – plalx Aug 14 '13 at 00:42
  • Yes, but in this case there is an available method called `.valid()` that eliminates the need to keep track of `.validate()`. Also, I'm just not sure that the benefit of jQuery not looking in the DOM a second time is worth the 40+ extra characters. Anyway, I suppose we're splitting hairs as there is nothing technically wrong here. – Sparky Aug 14 '13 at 00:57
1

I've created a little helper. Just add this line of code and then you can use any button anywhere.

$("body [data-submit-form]").on("click", function (event) {
    $("#" + $(event.target).data('submit-form')).valid();
});

<form id="component-form">

</form>

<button data-submit-form="component-form">Button</button>

Explanation: The jquery code listens for all clicks on an element with the attribute 'data-submit-form', in the listener the data-attribute gets extracted and then i trigger the valid method on the matching form.

NOTE: if you want to submit the form if the form is valid use this code:

$("body [data-submit-form]").on("click", function (event) {
    var form = $("#" + $(event.target).data('submit-form'));
    if (form.valid()) {
        form.submit();
    }
});
Simon Ludwig
  • 1,754
  • 1
  • 20
  • 27
0

Use this code for two sample fields email and password:-

<head>
    <script src="jquery-3.4.0.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #txt1{

        margin-left:23px;
        border-radius: 12px;
       }
       #txt2{
        border-radius: 12px;
       }
       #btn1{
        border-radius: 12px;
        width: 8em;  height: 2em;
        cursor:pointer;
        background-color: #008CBA;
       }
       #lbl1,#lbl2{
        font-family: "Comic Sans MS", cursive, sans-serif;
        color:red;
       }
    </style>
</head>

<body>
    <div class="container">
        <form>
            <center> <label id="lbl1">Email: </label><input type="text" id="txt1"></center></input><br>
            <center><label id="lbl2">Password: </label><input type="password" id="txt2"></center></input>
            <br><br>
            <center><input type="button" id="btn1" name="btn1" value="Login" style="color:darkblue;font-size:15px;"></center></input>
        </form>

    </div>
    <script>
        $(document).ready(function () {
            $('#btn1').click(function () {
                var email = $('#txt1').val();
                var pass = $('#txt2').val();
                if (email == '') {
                    $('input[type="text"]').css("border", "2px solid red");
                    $("#txt1").parent().after("<div class='validation' style='color:red;margin-left:93px;'><center>Please enter email address</center></div>");
                    alert("hi");
                }
                else {

                }
                if (pass == '') {
                    $('input[type="password"]').css("border", "2px solid red");
                    $("#txt2").parent().after("<div class='validationp' style='color:red;margin-left:70px;'><center>Please enter password</center></div>");
                }
                $('input[type="text"]').keydown(function () {
                    $('input[type="text"]').css("border", "");
                    $(".validation").remove();
                });
                $('input[type="password"]').keydown(function () {
                    $('input[type="password"]').css("border", "");
                    $(".validationp").remove();

                });

            });
        });

    </script>
</body>

</html>
-5

Just call the form submit method using jquery

$("#formId").submit()

This will validate entire form, same as when we click the submit button

Venkatachalam
  • 16,288
  • 9
  • 49
  • 77
Rejeesh
  • 1
  • 2