在Bootstrap中定义一个`required`字段

mot*_*rcb 61 twitter-bootstrap twitter-bootstrap-3

如何在Twitter Bootstrap 3中根据需要定义文本字段(带红色边框)?

required="required" 不起作用......

<form role="form">
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <div class="form-group">
    <label for="exampleInputFile">File input</label>
    <input type="file" id="exampleInputFile">
    <p class="help-block">Example block-level help text here.</p>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox"> Check me out
    </label>
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

vma*_*vma 82

尝试required="true"在bootstrap中使用3

  • 对我没什么用. (27认同)
  • 也许它没有做任何事,因为你在处理表单提交的函数中返回false或e.preventDefault.即:$('#my_button').on('click',function(e){/*my code;*/return false;}); 将阻止所需的属性工作.只需返回true或删除返回 (5认同)

Zim*_*Zim 58

更新2018年

由于现在所有现代浏览器都支持原始答案HTML5验证.现在,制作所需字段的最简单方法就是使用所需的属性.

<input type="email" class="form-control" id="exampleInputEmail1" required>

或符合HTML5:

<input type="email" class="form-control" id="exampleInputEmail1" required="true">
Run Code Online (Sandbox Code Playgroud)

阅读有关Bootstrap 4验证的更多信息


在Bootstrap 3中,您可以将"验证状态"类应用于父元素:http://getbootstrap.com/css/#forms-control-validation

例如,has-error将在输入周围显示红色边框.但是,这对现场的实际验证没有影响.您需要添加一些额外的客户端(javascript)或服务器逻辑才能使该字段成为必需.

演示:http://bootply.com/90564


  • @motorcb我想你没看过Skelly最后的评论 (7认同)

小智 5

可以通过data-api或JavaScript在标记中启用表单验证.通过添加data-toggle="validator"到表单元素自动启用表单验证.

<form role="form" data-toggle="validator">
   ...
</form>
Run Code Online (Sandbox Code Playgroud)

或者通过JavaScript激活验证:

$('#myForm').validator()
Run Code Online (Sandbox Code Playgroud)

并且您需要在输入字段中使用必需的标志

有关详细信息,请单击此处

  • 你忘了提到这不是bootstrap本身的一个特性,所以需要一个插件. (11认同)