Skip to content

Default validation rules

Greg Bowler edited this page Feb 28, 2023 · 7 revisions

The HTML Standard specifies a number of constraints that are implemented as standard as part of DomValidation, and are listed on this page with examples of how to use them.

Required fields

  • required boolean attribute

Specifies whether a form field needs to be filled in before the form can be submitted. This attribute is boolean meaning to use it, it just needs to be present.

If any elements with the required are not filled in when the form is submitted, this will trigger an error with the hint message "This field is required".

Example:

<form>
	<label>
		<span>Your name, please</span>
		<input name="your-name" required />
	</label>

	<button>Submit</button>
</form>

Text length

  • minlength attribute - integer, 0 or higher
  • maxlength attribute - integer, 0 or higher

Specified the minimum and maximum number of characters an element's value can contain.

If any elements with the minlength attribute are submitted with fewer than the required number of characters, this will trigger an error with the hint message "This field's value must contain at least X characters".

If any elements with the maxlength attribute are submitted with more than the required number of characters, this will trigger an error with the hint message "This field's value must not contain more than X characters".

Example:

<form>
	<label>
		<span>New password:</span>
		<input type="password" name="new-password" minlength="12" />
	</label>
</form>

Value ranges

  • min attribute
  • max attribute

The min attribute defines the minimum that is acceptable and valid for the input containing the attribute. The max attribute defines the maximum value that is acceptable and valid for the input containing the attribute.

Different input types have different minimum/maximum syntaxes.

Example (from MDN):

Input type Syntax Example
date yyyy-mm-dd <input type="date" min="2019-12-25" step="1" />
month yyyy-mm <input type="month" min="2019-12" step="12" />
week yyyy-W## <input type="week" min="2019-W23" step="" />
time hh:mm <input type="time" min="09:00" step="900" />
datetime-local yyyy-mm-ddThh:mm <input type="datetime-local" min="2019-12-25T19:30" />
number (number) <input type="number" min="0" step="5" max="100" />
range (number) <input type="range" min="60" step="5" max="100" />

Preset patterns of text

Custom regular expression patterns

Clone this wiki locally