Validation | required=“true” / “false” | HTML form

2020-07-09 08:35发布

While I was doing some basic HTML I was wondering why Sublime Text 3 always completes required into required="" . Like my Instructor in an online course said it is not necessary to set required="true" or required="false" but when I set it to false it still requires it.

example code (it will require the field even if it is set tofalse):

<form>
    <input type="password" name="password" required="false">
    <button>Submit</button>
</form>


I hope you can clear up the confusion. Thanks for every answer.

Farcher

4条回答
干净又极端
2楼-- · 2020-07-09 08:52

In HTML, the required attribute must be present (the field is required) or absent (the field is NOT required). When the attribute is present, it does not matter what value it has.

The required attribute is a boolean attribute. When specified, the element is required.

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

About boolean attributes:

A boolean attribute without a value assigned to it (e.g. checked) is implicitly equivalent to one that has the empty string assigned to it (i.e. checked=""). As a consequence, it represents the true value.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

A common practice is to use the name of the attribute as its value:

<form>
    <input type="password" name="password" required="required"><!-- this input is required -->

    <input type="text" name="sometext"><!-- this input is NOT required -->

    <button>Submit</button>
</form>
查看更多
The star\"
3楼-- · 2020-07-09 09:00

'Required' is a Boolean attribute. It assumes the value of true once it is present. therefore setting it to a 'false' still makes it act as though it was true.

Below is proof

<form>
<input type="password" name="password" required="false">
<button>Submit</button>
</form>
查看更多
Melony?
4楼-- · 2020-07-09 09:02

However, if one is handling mouse events, for instance, using JS, they can set the "required" attribute to "True" or "False" using the ".prop()" method. e.g.

.prop("required", true) 

OR

.prop("required", false)
查看更多
冷血范
5楼-- · 2020-07-09 09:03

required doesn't take a boolean string. It's required if the attribute exists at all. Sublime is likely expecting some value like most attributes.

<form>
<input type="password" name="password" required="">
<button>Submit</button>
</form>

<form>
<input type="password" name="password" required>
<button>Submit</button>
</form>

查看更多
登录 后发表回答