0

I have multiple forms on a ASP.NET web form (which are actually div tags since I can have only 1 form tag on the web form) , and I've applied the HTML required attribute on my input fields. Each form may be submitted independently, and I'd like the validations to work independently on each form. However, if I submit the second form, the browser indicates that the fields of the first form are required.

HTML:

<form id="myform" runat="server">
    <div id="div1" class="form">
        <input type="text" name="field1" required="required" />
        <br/>
        <input type="text" name="field2" required="required" />
        <br/>
        <input type="submit" id="btn1" />
    </div>
    <div id="div2" class="form">
        <input type="text" name="field3" required="required" />
        <br/>
        <input type="text" name="field4" required="required" />
        <br/>
        <input type="submit" id="btn2" />
    </div>
</form>

JS:

$(document).ready(function () {

    $('.form').each(function () {
        $(this).validate({
            submitHandler: function (form) { // for demo
                alert('valid form');
                return false;
            }
        });
    });

    $('#btn1').click(function (e) {
        var formValid = true;
        // loop through all input controls
        $('#div1 input').each(function () {
            //use HTML5 checkValidity function
            if (this.checkValidity()) {              
                //do something
            } else {
                //do something else
                formValid = false;
            }
        });
        if (!formValid) {
            alert('Form 1 invalid');
        } else {
            alert('Form 1 valid');
        }
    });

    $('#btn2').click(function (e) {
        var formValid = true;
        // loop through all input controls
        $('#div2 input').each(function () {
            //use HTML5 checkValidity function
            if (this.checkValidity()) {
                //do something
            } else {
                //do something else
                formValid = false;
            }
        });
        if (!formValid) {
            alert('Form 2 invalid');
        } else {
            alert('Form 2 valid');
        }
    });
});

Created a JSFiddle for the same: http://jsfiddle.net/6Fs9y/132/

Basically, I want to validate only the input and not the entire form. I've tried using both this.checkValidity() and this.validity.valid, but both exhibit the same behavior. Also, if I use the novalidate tag with a return false when an error is encountered, the popup message indicating that the field is required doesn't show up anymore (http://jsfiddle.net/6Fs9y/133/).

Is there any way this can be done?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Fahad
  • 1,364
  • 3
  • 20
  • 40

0 Answers0