单选按钮只需要一个验证和错误消息

时间:2017-05-02 09:41:09

标签: jquery radio-button

我想只允许检查一组单选按钮,并通过显示错误消息来验证何时没有选中任何选项。

这就是我所做的FIDDLE

(function($, W, D) {
  var JQUERY4U = {};

  JQUERY4U.UTIL = {
    setupFormValidation: function() {
      //form validation rules

      // Setup form validation on the #register-form element
      $("#requestAr").validate({
        errorElement: 'div',
        rules: {
          requestType: {
            checkType: true,
          },
          requester: {
            required: true,
          },
        },
        messages: {
          requester: {
            required: "Enter your name",
          },
        },
        submitHandler: function(form) {
          form.submit();
        }
      });

    }
  };

  $(D).ready(function($) {
    JQUERY4U.UTIL.setupFormValidation();

    jQuery.validator.addMethod('checkType', function(value) {
      return ($(value).is(':checked'));
    }, "Choose request type");
  });
})(jQuery, window, document);

我无法使其工作,即使我检查了一个选项仍然显示验证错误并拒绝提交表单

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

HTML:

<form id="frm">
  <div class="formLayout">
    <div class="required">
      <label>Request Type</label>
      <legend>
        Article
        <input type="radio" name="requestType" value="Article"/>
        e-Article
        <input type="radio" name="requestType" value="eArticle"/>
        Chapter
        <input type="radio" name="requestType" value="Chapter"/>
      </legend>
    </div>
    <!-- Error label -->
    <label id="requestType-error" class="error" for="requestType"></label>
  </div>
  <input type="submit" value="submit">
</form>

Jquery的:

$('#frm').validate({
    rules: {
    requestType: {
        required: true
    }
  }
});

Working Fiddle