Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

<input type="url">

BaselineWidely available

<input> elements of typeurl are used to let the user enter and edit a URL.

Try it

<form>  <label for="url">Enter an https:// URL:</label>  <input    type="url"    name="url"       placeholder="https://example.com"    pattern="https://.*"    size="30"    required /></form>
label {  display: block;  font:    1rem "Fira Sans",    sans-serif;}input,label {  margin: 0.4rem 0;}

The input value is automatically validated to ensure that it's either empty or a properly-formatted URL before the form can be submitted. The:valid and:invalid CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid URL or not.

Value

The<input> element'svalue attribute contains a string that is automatically validated as conforming to URL syntax. More specifically, there are two possible value formats that will pass validation:

  1. An empty string ("") indicates the user did not enter a value or that the value was removed.
  2. A single properly-formed absolute URL. This doesn't necessarily mean the URL address exists, but it is at least formatted correctly. An entry matchingurlscheme://rest-of-url can be valid, even if theurlscheme entered doesn't exist.

SeeValidation for details on how URLs are validated to ensure that they're formatted properly.

Additional attributes

In addition to theglobal attributes, and the attributes that operate on all<input> elements regardless of their type,url inputs support the following attributes.

Note:Theautocorrect global attribute can be added to url inputs, but the stored state is alwaysoff.

list

The values of the list attribute is theid of a<datalist> element located in the same document. The<datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with thetype are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

maxlength

The maximum string length (measured inUTF-16 code units) that the user can enter into theurl input. This must be an integer value of0 or higher. If nomaxlength is specified, or an invalid value is specified, theurl input has no maximum length. This value must also be greater than or equal to the value ofminlength.

The input will failconstraint validation if the length of the text value of the field is greater thanmaxlengthUTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

minlength

The minimum string length (measured inUTF-16 code units) that the user can enter into theurl input. This must be a non-negative integer value smaller than or equal to the value specified bymaxlength. If nominlength is specified, or an invalid value is specified, theurl input has no minimum length.

The input will failconstraint validation if the length of the text entered into the field is fewer thanminlengthUTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

pattern

Thepattern attribute, when specified, is a regular expression that the input'svalue must match for the value to passconstraint validation. It must be a valid JavaScript regular expression, as used by theRegExp type, and as documented in ourguide on regular expressions; the'u' flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of asASCII. No forward slashes should be specified around the pattern text.

If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

Note:Use thetitle attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.

See the sectionPattern validation for details and an example.

placeholder

Theplaceholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The textmust not include carriage returns or line feeds.

If the control's content has one directionality (LTR orRTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; seeHow to use Unicode controls for bidi text for more information.

Note:Avoid using theplaceholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See<input> labels for more information.

readonly

Thereadonly Boolean attribute, if present, means this field cannot be edited by the user. Itsvalue can, however, still be changed by JavaScript code directly setting theHTMLInputElementvalue property.

Note:Because a read-only field cannot have a value,required does not have any effect on inputs with thereadonly attribute also specified.

size

Thesize attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (font settings in use).

This doesnot set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use themaxlength attribute.

spellcheck

Thespellcheck global attribute is used to indicate whether to enable spell-checking for an element. It can be used on any editable content, but here we consider specifics related to the use ofspellcheck on<input> elements. The permitted values forspellcheck are:

false

Disable spell-checking for this element.

true

Enable spell-checking for this element.

"" (empty string) or no value

Follow the element's default behavior for spell-checking. This may be based upon a parent'sspellcheck setting or other factors.

An input field can have spell-checking enabled if it doesn't have thereadonly attribute set and is not disabled.

The value returned by readingspellcheck may not reflect the actual state of spell-checking within a control if theuser agent's preferences override the setting.

Using URL inputs

When you create a URL input with the propertype value,url, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mistypes their website's address, or provides an invalid one.

It's important, however, to note that this is not enough to ensure that the specified text is a URL which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be a URL.

Note:A user can tinker with your HTML behind the scenes, so your sitemust not use this validation for any security purposes. Youmust verify the URL on the server-side of any transaction in which the provided text may have any security implications of any kind.

A basic URL input

This element is implemented as a standard text input field with basic validation features. In its most basic form, a URL input can be implemented like this:

html
<input name="myURL" type="url" />

Notice that it's considered valid when empty and when a single validly-formatted URL address is entered, but is otherwise not considered valid. By adding therequired attribute, only properly-formed URLs are allowed; the input is no longer considered valid when empty.

There is nothing magical going on here. Submitting this form would cause the following data to be sent to the server:myURL=http%3A%2F%2Fwww.example.com. Note how characters are escaped as necessary.

Placeholders

Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each<input>. This is whereplaceholders come in. A placeholder is a value that demonstrates the form thevalue should take by presenting an example of a valid value, which is displayed inside the edit box when the element'svalue is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

Here, we have aurl input with the placeholderhttp://www.example.com. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

html
<input   name="myURL"  type="url"  placeholder="http://www.example.com" />

Controlling the input size

You can control both the physical length of the input box and the minimum and maximum lengths allowed for the input text.

Physical input element size

The physical size of the input box can be controlled using thesize attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, theurl edit box is 30 characters wide:

html
<input name="myURL" type="url" size="30" />

Element value length

Thesize is separate from the length limitation on the entered URL itself. You can specify a minimum length, in characters, for the entered URL using theminlength attribute; similarly, usemaxlength to set the maximum length of the entered URL. IfmaxLength exceedssize, the input box's contents will scroll as needed to show the current selection or insertion point as the content is manipulated.

The example below creates a 30-character wide URL address entry box, requiring that the contents be no shorter than 10 characters and no longer than 80 characters.

html
<input   name="myURL"  type="url"  size="30"  minlength="10"  maxlength="80" />

Note:These attributes also affect validation; a value shorter or longer than the specified minimum/maximum lengths will be classified as invalid; in addition most browsers will refuse to let the user enter a value longer than the specified maximum length.

Providing default options

Providing a single default using the value attribute

As always, you can provide a default value for aurl input box by setting itsvalue attribute:

html
<input name="myURL" type="url" value="http://www.example.com" />

Offering suggested values

Taking it a step further, you can provide a list of default options from which the user can select by specifying thelist attribute. This doesn't limit the user to those options, but does allow them to select commonly-used URLs more quickly. This also offers hints toautocomplete. Thelist attribute specifies the ID of a<datalist>, which in turn contains one<option> element per suggested value; eachoption'svalue is the corresponding suggested value for the URL entry box.

html
<input name="myURL" type="url" list="defaultURLs" /><datalist>  <option value="https://developer.mozilla.org/"></option>  <option value="http://www.google.com/"></option>  <option value="http://www.microsoft.com/"></option>  <option value="https://www.mozilla.org/"></option>  <option value="http://w3.org/"></option></datalist>

With the<datalist> element and its<option>s in place, the browser will offer the specified values as potential values for the URL; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested URLs. Then, as the user types, the list is adjusted to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

Using labels for suggested values

You can opt to include thelabel attribute on one or all of your<option> elements to provide textual labels. Some browsers may display only the labels, while others may display both the label and the URL.

html
<input name="myURL" type="url" list="defaultURLs" /><datalist>  <option value="https://developer.mozilla.org/" label="MDN Web Docs"></option>  <option value="http://www.google.com/" label="Google"></option>  <option value="http://www.microsoft.com/" label="Microsoft"></option>  <option value="https://www.mozilla.org/" label="Mozilla"></option>  <option value="http://w3.org/" label="W3C"></option></datalist>

Validation

There are two levels of content validation available forurl inputs. First, there's the standard level of validation offered to all<input>s, which automatically ensures that the contents meet the requirements to be a valid URL. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any.

Warning:HTML form validation isnot a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.

Basic validation

Browsers that support theurl input type automatically provide validation to ensure that only text that matches the standard format for URLs is entered into the input box.

The syntax of a URL is fairly intricate. It's defined by WHATWG'sURL Living Standard and is described for newcomers in our articleWhat is a URL?

Making a URL required

As mentioned earlier, to make a URL entry required before the form can be submitted (you can't leave the field blank), you just need to include therequired attribute on the input.

Pattern validation

If you need the entered URL to be restricted further than just "any string that looks like a URL," you can use thepattern attribute to specify aregular expression the value must match for the value to be valid.

Examples

URL validation

In this example, we make sure that a URL is filled in using therequired attribute and that the URL is something onmozilla.org using thepattern attribute for illustration.

HTML

In theurl input, we setpattern to".*\.mozilla\.org.*". This regular expression validates a string that has any number of characters, followed by ".mozilla.org", followed by any number of characters. Because the browser runs both the standard URL filterand our custom pattern against the specified text, we wind up with a validation that says "make sure this is a valid URL, and also contains.mozilla.org."

Note that a strict pattern likehttps://developer\.mozilla\.org.* would be more robust, but that would make thetype="url" attribute redundant in this case.

Thetitle attribute also describes thepattern for users with assistive technologies.

html
<form>  <label for="myURL">    Enter a url from this site:    <input           name="myURL"      type="url"      required      pattern=".*\.mozilla\.org.*"      title="URL should include mozilla.org" />    <span></span>  </label>  <button>Submit</button></form>

CSS

The CSS gives visual clues to show the user if the content is:valid or:invalid by adding an appropriatecontent property and includesalternative text for users with assistive technologies.

css
input:focus:invalid {  outline: 2px solid red;}input:focus:valid {  outline: 2px solid green;}input + span {  padding: 0 0.3rem;}input:invalid + span::after {  content: "✖" / "Content is not valid";  color: red;}input:valid + span::after {  content: "✓" / "Content is valid";  color: green;}

Result

Copy this page's url and paste it in the input field and you will see a green outline and green tick. Enter any other URL that doesn't containmozilla.org or an invalid URL and you will see a red outline and red cross.

Check thePattern validation andUsing URL inputs sections for other examples.

Technical summary

ValueA string representing a URL, or empty
Eventschange andinput
Supported Common Attributesautocomplete,list,maxlength,minlength,pattern,placeholder,readonly,required andsize
IDL attributeslist,value,selectionEnd,selectionDirection
DOM interfaceHTMLInputElement
Methodsselect(),setRangeText() andsetSelectionRange().
Implicit ARIA Rolewith nolist attribute:textboxwithlist attribute:combobox

Specifications

Specification
HTML
# url-state-(type=url)

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp