简体   繁体   English

自定义 html5 验证 select

[英]Custom html5 validation for select

I have a element select like this:我有一个元素 select 像这样:

<select name="select">
<option value="opt1">Select One Value Only</option>
<option value="opt2">Type 2</option>
<option value="opt3">Type 3</option>
</select>

and I want user to select a option eg opt2, opt3... but opt1, how to to use html 5 validation to valid the select?我希望用户使用 select 一个选项,例如 opt2、opt3 ......但是 opt1,如何使用 html 5 验证来验证 select?

You can do something like the following:您可以执行以下操作:

 <select name="select"> <option value="opt1" selected disabled>Select One Value Only</option> <option value="opt2">Type 2</option> <option value="opt3">Type 3</option> </select>

In the snippet above, the opt1 is selected by default.在上面的代码片段中,默认选择opt1 The user can only select opt2 or opt3 , but once they do that then they cannot selecte opt1 , hope this is the behaviour you're looking for.用户只能 select opt2opt3 ,但一旦他们这样做,他们就无法选择opt1 ,希望这是您正在寻找的行为。

I think the only way to add the validation here is to set the default option value to an empty string and add required attribute to select element.我认为在此处添加验证的唯一方法是将默认选项值设置为空字符串并将required属性添加到select元素。 Now you can click on submit button to see the validation:现在您可以单击提交按钮查看验证:

 <form> <label >Choose an option:</label> <select name="select" required> <option value="" disabled selected>Select One Value Only</option> <option value="opt2">Type 2</option> <option value="opt3">Type 3</option> </select> <input type="submit"> </form>

The issue here is that when you set a value to the default option to something other than empty string the validation infers it as a valid value has been already selected, thus the validation is not triggered at that point.这里的问题是,当您将默认选项设置为空字符串以外的其他值时,验证会将其推断为已选择有效值,因此此时不会触发验证。

Try Using:尝试使用:

<select name="select" required>
  <option value="opt1" selected="selected" disabled>Select One Value Only</option>
  <option value="opt2">Type 2</option>
  <option value="opt3">Type 3</option>
</select>

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

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