【问题标题】:How to Validate input inside of a radio button?如何验证单选按钮内的输入?
【发布时间】:2016-12-12 18:17:21
【问题描述】:

我为此使用 jquery validate 并有 3 个单选按钮,其中两个有一个可以输入价格的输入。我需要它,所以必须选择 3 个单选按钮中的一个,如果它是前 2 个单选按钮之一,我需要它们在那里也有价格。我需要以某种方式创建一个额外的方法吗?我在页面上包含了我正在使用的其他一些验证,但 html 只显示了我正在处理的部分。

    // Validation
$(document).ready(function () {

        jQuery.validator.addMethod("noSpace", function(value, element) { 
          return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
        }, "Please specify the correct domain for your documents");


        jQuery.validator.addMethod("checkmeout", function(value, element) { 
            return this.optional(element) || /^\s*[0-9a-zA-Z][0-9a-zA-Z ]*$/.test(value);
        },"Required");

        $('#addProductForm').validate({
            rules: {
                productName: {
                    minlength: 2,
                    maxlength: 40,
                    required: true,
                    checkmeout: true
                },
                categoryPlaceholder: {
                    required: true,
                    errorClass: "testing"
                },
                productDescriptionShort: {
                    minlength: 2,
                    maxlength: 250,
                    required: false,
                    checkmeout: true
                },
                productDetailsLong: {
                    minlength: 2,
                    maxlength: 500,
                    required: true,
                    checkmeout: true
                },
                 productFCState: {
                    required: true
                },
                 productCategory: {
                    required: true
                }
            },

            messages: {
                    productName: {
                        minlength: "Your product name must be between 2 and 40 characters",
                        required: ""
                    }, 
                    categoryPlaceholder: {
                        required: ""
                    },
                    productDescriptionShort: {
                        minlength: "Your product description must be between 2 and 250 characters",
                        required: ""
                    },
                    productDetailsLong: {
                        minlength: "Your product description must be between 2 and 500 characters",
                        required: ""
                    },
            },

            highlight: function(element) {
                $(element).closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element).closest('.form-group').removeClass('has-error');
            },

            errorElement: 'span',
            errorClass: 'help-block-error',
            errorPlacement: function(error, element) {
                if(element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                } else if(element.parent('#productCategory').length) {
                    error.insertAfter('.list-group.list-group-root');
                } else {
                    error.insertAfter(element);
                }
            }
        });
});
</script>
#itemFeatured {
    margin-bottom: 0;
}

.radio label::after {
    background-color: #3390ce;
}

.height-initial {
    height: initial;
}

#itemPricing .form-inline {
    margin-bottom: 20px;
}

#itemPricing .form-inline label {
    width: 120px;
    padding-left: 5px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesome-bootstrap-checkbox/0.3.7/awesome-bootstrap-checkbox.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>




 <form id="addProductForm">
<div id="itemPricing" class="clearfix">
  <div class="row">
    <div class="col-sm-12" form-group="">
      <label for="itemPricing" class="required" aria-required="true">Pricing</label>
      <span id="helpBlock" class="help-block">Select how you want pricing to display on your website.</span>
    </div>

    <!-- Regular Price -->
    <div class="col-sm-12 form-group">
      <div class="form-inline radio-input-group">
        <div class="radio">
          <input type="radio" class="height-initial" name="pricingOptions" id="regularPrice" value="">
          <label for="regularPrice" class="required" aria-required="true">Regular Price</label>
        </div>
        <div class="input-group">
          <span class="input-group-addon">$</span>
          <input type="text" class="form-control money" id="productPrice" name="productPrice">
        </div>
      </div>
      <div class="form-inline radio-input-group">
        <div class="radio">
          <input type="radio" class="height-initial" name="pricingOptions" id="salePrice" value="">
          <label for="salePrice" class="required" aria-required="true">Sale Price</label>
        </div>
        <div class="input-group">
          <span class="input-group-addon">$</span>
          <input type="text" class="form-control money" id="productPrice" name="productPrice">
        </div>
      </div>
      <div class="form-inline radio-input-group">
        <div class="radio">
          <input type="radio" class="height-initial" name="pricingOptions" id="emailPrice" value="">
          <label for="emailPrice" class="required" aria-required="true">Email for Price</label>
        </div>
      </div>
    </div>
  </div>
</div>
   <div class="pull-right">
                              <button type="submit" class="btn btn-success save ladda-button" data-style="zoom-in">Save</button>
                            </div>
</form>

【问题讨论】:

  • 你的问题有点不清楚。请解释一下。
  • 我怎样才能验证这个表格,以便这个组是必需的,因为用户必须选择一个单选选项,如果它是前两个选项之一,他们还必须在输入。
  • 您不小心在页面上重复了两次 productPrice 字段。

标签: jquery twitter-bootstrap jquery-validate


【解决方案1】:

我如何验证此表单以便需要此组,因为用户必须选择其中一个单选选项...?

只需将其设为required

$('#addProductForm').validate({
    rules: {
        pricingOptions: {
            required: true
        }, ....

然后您必须有条件地调整 errorPlacement


...如果是前两个之一,它们的输入中也必须有一个数字?

根据单选选项有条件地将required 规则应用于文本字段...

$('#addProductForm').validate({
    rules: {
        pricingOptions: {
            required: true
        },
        productPrice: {
            required: function(element) {
                return $('#regularPrice').is(':checked');
            }
        },
        productPriceSale: {
            required: function(element) {
                return $('#salePrice').is(':checked');
            }
        }, ....

您不小心在页面上重复了两次 productPrice 字段。你不能有重复的id


演示jsfiddle.net/spr29o36/

【讨论】:

  • 知道为什么突出显示没有将 has-error 类添加到最近的表单组吗?我想用它来应用一些 css 来直观地显示它有错误
  • @JacobJ,它确实添加了类。禁用unhighlight 以亲自查看。问题是unhighight 函数同时被表单上的有效字段触发。您的 highlightunhighlight 函数太通用了....多个字段针对相同的 closest('form-group')
【解决方案2】:

首先,你应该链接你本地的js文件,否则浏览器无法执行:

<script src="yourfile.js"></script>

接下来你必须给你在js中需要的每一个表单一个id,在这种情况下,你必须给按钮一个id,例如,将你的html行改为这个:

<button id="saveButton" type="submit" class="btn btn-success save ladda-button" data-style="zoom-in">Save</button>

现在您可以访问该按钮,并且可以验证您想要的任何内容:

$(document).ready(function () {
    $("#saveButton").click(function(){
        switch($('input[name=pricingOptions]:checked').val()){
            case "1": 
                if($("#productPrice").val() == "")
                    console.log("bad");
                else console.log("good");
                break;
            case "2": 
                if($("#salePrice").val() == "")
                    console.log("bad");
                else console.log("good"); break;
            case "3": console.log("good"); break;
            default: console.log("bad");
        }
    });
});

请注意,我采用了定价选项的值,在 HTML 文件中,您必须为每个单选选项赋予不同的值。

【讨论】:

  • 请注意,OP 正在询问如何使用 jQuery Validate 插件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多