简体   繁体   English

两种表单HTML,仅验证提交的表单

[英]Two forms HTML, validate only submitted form

I have two forms on a single page. 我在一个页面上有两种形式。 One is just a form for the particular page it's on and the other is a side form that is on every page. 一个只是用于其上特定页面的表单,另一种是每一页上的侧面表单。 I have gotten a validator to work to format the error ridden fields; 我已经得到了一个验证器,以对出错的字段进行格式化。 it shows red boxes around fields that are incomplete. 它在不完整的字段周围显示红色框。 This works on the first form however if you submit the second form, it will still format the first form only. 这适用于第一个表单,但是,如果您提交第二个表单,它将仍然仅格式化第一个表单。 I have taken out the code for the first form, and the second side form works perfectly. 我已经取出了第一种形式的代码,而第二种形式则完美地工作了。 My question is how can I get the validator to check and submit only the form which is clicked? 我的问题是如何让验证器检查并仅提交被单击的表单? I have made a short test page to illustrate the problem. 我做了一个简短的测试页来说明问题。

<!DOCTYPE >
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/jquery.maskedinput.js"></script>
<script type="text/javascript" src="js/mktSignup.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="css/css.css">
</head>
<body>
<!-- When you submit this form the appropriate red boxes are shown around the errored fields-->
<form id="requestAppointment" method="post" type="actionForm"  action="." name="requestFreeConsultation">
    <label for="name">Your Name</label><br>
    <input type="text" class="stdFormFieldSml defaultInvalid" value="First Name" name="firstName" id="firstName" onclick="if(this.value=='First Name')this.value='';" />
    <input type="submit" name="firstForm" value="Submit" />
</form>
<!-- This form when you hit submit causes red boxes around the previous form's incomplete fields-->
<form name="freeConsultationWidget" action="thank-you.php" method="post">
    <label for="nameMini">Your Name</label><br>
    <input type="text" class="stdFormFieldSml defaultInvalid" value="First Name" name="firstNameMini" id="firstNameMini" onclick="if(this.value=='First Name')this.value='';" />
    <input type="image" name="secondForm" value="submit1"/>
</form>
</body>
</html>

As everyone has suggested I am going to post the js file. 正如每个人都建议的那样,我将发布js文件。 (I am not posting the standard jquery validate file.) (我没有发布标准的jQuery验证文件。)

    $(document).ready(function(){

    jQuery.validator.addMethod("password", function( value, element ) {
        var result = this.optional(element) || value.length >= 6 && /\d/.test(value) && /[a-z]/i.test(value);
        if (!result) {
            element.value = "";
            var validator = this;
            setTimeout(function() {
                validator.blockFocusCleanup = true;
                element.focus();
                validator.blockFocusCleanup = false;
            }, 1);
        }
        return result;
    }, "Your password must be at least 6 characters long and contain at least one number and one character.");

    // a custom method making the default value for companyurl ("http://") invalid, without displaying the "invalid url" message
    jQuery.validator.addMethod("defaultInvalid", function(value, element) {
        return value != element.defaultValue;
    }, "");

    jQuery.validator.addMethod("billingRequired", function(value, element) {
        if ($("#bill_to_co").is(":checked"))
            return $(element).parents(".subTable").length;
        return !this.optional(element);
    }, "");

    jQuery.validator.messages.required = "";
    $("form").validate({
        invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1
                    ? 'You missed 1 field. It has been highlighted below'
                    : 'You missed ' + errors + ' fields.  They have been highlighted below';
                $("div.error span").html(message);
                $("div.error").show();
            } else {
                $("div.error").hide();
            }
        },
        onkeyup: false,
        submitHandler: function() {
            $("div.error").hide();
            alert("submit! use link below to go to the other step");
        },
        messages: {
            password2: {
                required: " ",
                equalTo: "Please enter the same password as above"  
            },
            email: {
                required: " ",
                email: "Please enter a valid email address, example: you@yourdomain.com",
                remote: jQuery.validator.format("{0} is already taken, please enter a different address.")  
            }
        },
        debug:true
    });

  $("input.home").mask("(999) 999-9999");
  $("input.zipcode").mask("99999");
  $("input.ssNumber").mask("999-999-9999");

/*  
  var creditcard = $("ssNumber").mask("999-999-9999 9999");

  $("#cc_type").change(
    function() {
      switch ($(this).val()){
        case 'amex':
          creditcard.unmask().mask("9999 999999 99999");
          break;
        default:
          creditcard.unmask().mask("9999 9999 9999 9999");
          break;
      }
    }
  );
*/

/*
  // toggle optional billing address
  var subTableDiv = $("div.subTableDiv");
  var toggleCheck = $("input.toggleCheck");
  toggleCheck.is(":checked")
    ? subTableDiv.hide()
    : subTableDiv.show();
  $("input.toggleCheck").click(function() {
      if (this.checked == true) {
        subTableDiv.slideUp("medium");
        $("form").valid();
      } else {
        subTableDiv.slideDown("medium");
      }
  });
*/

});

$.fn.hoverClass = function(classname) {
    return this.hover(function() {
        $(this).addClass(classname);
    }, function() {
        $(this).removeClass(classname);
    });
};

it seems your validator script select first Form of the page, something like this 看来您的验证程序脚本选择了页面的第一个表单,类似这样

 //javascript code 
 var Form = document.forms[1]; , 

 // you need to select second form, using

 var Form2 = document.forms[2]; , 

You can try this in your script section, provided you are using jquery 您可以在脚本部分尝试此操作,前提是您正在使用jquery

$('form[name="requestAppointment"]').submit(function(){
   alert('From requestAppointment submited');// Test purpose
   // your logic
});

$('form[name="freeConsultationWidget"]').submit(function(){
   alert('From freeConsultationWidget submited');// Test purpose
   // your logic
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM