【问题标题】:unable to validate checkbox with [] [duplicate]无法使用 [] [重复] 验证复选框
【发布时间】:2016-03-12 10:03:30
【问题描述】:

好的,如果我将复选框房间字段放在不带 [] 的情况下,以下代码可以正常工作,但如果我喜欢这样

$(function() {

// Setup form validation on the #register-form element
$("#reservation").validate({

    // Specify the validation rules
    rules: {
        room[]: "required",
        start: "required",
        end: "required",
        name: "required",
        phone: "required",
        email: {
            required: true,
            email: true
        },
        address: "required"
    },

    // Specify the validation error messages
    messages: {
        room[]: "    Select one room",
        start: "Select Check In date in Room Availability",
        end: "Select Check Out date in Room Availability",
        name: "Enter your full name",
        phone: "Phone number is required",
        email: "Please enter a valid email address",
        address: "Address is required"
    },


    submitHandler: function(form) {
        form.submit();
    }
});

});

那么带有 room[] 的房间字段不会抛出任何错误来选择一个房间。

【问题讨论】:

  • 它抛出一个错误。 SyntaxError: Unexpected token [
  • 通过对对象字面量使用有效的语法。查看重复问题的各种答案。
  • 只有一个主题您发布了链接,我无法找到该帖子的答案兄弟。我是stackoverflow的新手

标签: jquery html css validation


【解决方案1】:

http://jqueryvalidation.org/files/demo/radio-checkbox-select-demo.html

更新工作示例:

http://codepen.io/anon/pen/RaGbeP

$(function() {
$('#myform').validate({
rules: {
  "room[]": {
    required: true
  }
},
messages: {
  "room[]": {
    required: "Please select a room<br/>"
  }
},
errorPlacement: function(error, element) {
  if (element.is(":radio")) {
    error.appendTo(element.parents('.container'));
  } else { // This is the default behavior 
    error.insertAfter(element);
  }
}
});

});

<form id="myform">
  <label for='room'>Select one room:</label>
  <p class='container'>
  <label><input type='checkbox' name='room[]' value='room one' />one</label>
  <label><input type='checkbox' name='room[]' value='room two' />two</label>
  <label><input type='checkbox' name='room[]' value='room three' />three</label>
</p>
<input type="submit" name="submit" value="Submit">
</form>

【讨论】:

  • 但我的复选框有多个值
  • OP 处理的是复选框,而不是单选按钮。 PHP 依赖于名称中包含 [] 以便接受单个名称的多个值。删除 [] 会破坏事情。
  • @Stuart 字段是复选框,因为用户可以选择多个选项,因此需要将输入字段作为复选框,因此名称应类似于 name="room[]"
  • 我们在这里讨论的是 jquery 验证,而不是 php 方面的东西!我说过要从验证规则中删除 [],如您在上面看到的,为了清楚起见,我已经编辑了 HTML...抱歉没有在初始代码粘贴中显示它们。
  • 是的@Stuart 它的 jquery 验证以为我知道我将它用于 php,但我需要它来验证带有 name="room[]" 的复选框
猜你喜欢
  • 2018-03-24
  • 2013-04-19
  • 2014-05-25
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2017-12-24
  • 2020-07-12
  • 2013-07-07
相关资源
最近更新 更多