Html input checkbox required

Атрибут required

Атрибут required добавляется обязательным полям формы. Если поле с таким атрибутом не заполнено, то при отправке формы браузер покажет предупреждение и отменит отправку.

Пример

Скопировать ссылку «Пример» Скопировано

В примере ниже поле для телефона является обязательным:

    Ваше имя:  Ваш номер телефона (обязательно):   form> label> Ваше имя: input type="text"> label> label> Ваш номер телефона (обязательно): input type="tel" required> label> button type="submit">Отправить заявкуbutton> form>      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Достаточно написать атрибут required без значения, ведь он булевый: если он есть — поле обязательное, а если нет — не обязательное. Если вам по какой-то причине нельзя использовать булевы атрибуты (например, в XML-разметке), напишите required = «required» .

Атрибут required можно использовать для , , а также для со следующими типами:

  • text ,
  • search ,
  • url ,
  • tel ,
  • email ,
  • password ,
  • date ,
  • month ,
  • week ,
  • time ,
  • datetime — local ,
  • number ,
  • checkbox ,
  • radio ,
  • file .

Если в группе радиокнопок с одинаковым значением атрибута name хотя бы у одной указан атрибут required , то вся группа будет считаться обязательной. Поэтому лучше явно прописывать required всем радиокнопкам в группе. При этом для чекбоксов с одинаковыми именами это не работает. Обязательным будет только тот чекбокс, у которого прописан атрибут.

Атрибут не сработает для любых кнопок, а также для полей ввода с типами color и range . Причина в том, что у таких полей существует значение по умолчанию, даже если оно явно не прописано в атрибуте value . У это #000000 , а у это среднее значение между min и max . Так что браузер посчитает их заполненными в любом случае и не покажет предупреждение.

Кроме того, атрибут required не работает для скрытых полей type = «hidden» и для полей с атрибутом readonly .

Как понять

Скопировать ссылку «Как понять» Скопировано

В момент отправки формы браузер выполняет валидацию введённых данных. Если поле, у которого есть атрибут required , не заполнено, то браузер не позволит отправить форму и покажет сообщение. Внешний вид и текст сообщения может отличаться в разных браузерах. Сообщение в Google Chrome:

Сообщение «заполните это поле» при отправке формы с обязательным полем

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Поля с атрибутом required можно стилизовать при помощи псевдокласса :required . Поля, у которых нет этого атрибута, стилизуются псевдоклассом :optional .

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 Необходимо визуально выделять обязательные для заполнения поля формы. Почему-то исторически сложилось, что рядом с подписью для поля ставят звёздочку. Раньше под формой писали пояснение, что звёздочка значит обязательное поле. Но со временем пропало даже пояснение.

Звёздочка — плохой паттерн. Как минимум потому что скринридер прочитает её просто как «звёздочка». Лучше явно написать в скобках «(обязательное)». Тогда пользователь, каким бы инструментом он не пользовался, точно будет знать, что поле надо заполнить.

Источник

HTML Form Checkbox with required validation

The code below shows how to create a single checkbox with “required” validation. Make sure you have not selected the checkbox and then press the submit button to see the error message.

Required Validation for a group of checkboxes

Although the HTML5 ‘required’ validation will work fine with Single checkboxes, there is no HTML5 validation for a group of checkboxes. You will have to do the validation using Javascript.

Here is the validation function for more clarity:

function handleData()   var form_data = new FormData(document.querySelector("form"));   if(!form_data.has("langs[]"))    document.getElementById("chk_option_error").style.visibility = "visible";  >  else    document.getElementById("chk_option_error").style.visibility = "hidden";  >  return false; > 

The function collects the FormData() from the form element and check for langs variable. If none of the options are selected, the langs options should be empty.

See Also

Источник

HTML: Validating a checkbox with HTML5

While HTML5 form validation is typically about missing or invalid text inputs, there are other form element types that also require attention. One of them being the humble checkbox.

Checkbox validation using JavaScript

Suppose you have a form on your website that at the bottom asks people to «accept the Terms and Conditions» or something similar. Basically you don’t want the form to be submitted unless this is checked.

Using vanilla JavaScript we can prevent form submission as follows:

All this does is confirm before submitting the form that the checkbox is checked. If not, an alert is displayed and focus is moved to the checkbox. Not the prettiest solution, but functional in all browsers that have JavaScript enabled.

HTML5 required input

Adding HTML5 validation to the checkbox is actually very simple. All you need to do is include a required attribute:

This tells the browser that the form should not be allowed to submit without the checkbox checked. Some, but not all, browsers will recognise and enforce this:

The advantage of the HTML5 form validation is that it happens before our JavaScript is called, displays instructions and points the user to the relevant element.

Here you can see screen captures from Firefox and Chrome:

Text alert messages are generated entirely by the browser and will even translate automatically into different languages — something that would be almost impossible using just JavaScript.

The advantage for the user is that it’s obvious whick element is causing the problem and there’s no alert window that needs to be clicked away.

If you’re using an unsupporting browsers all the examples will just display the JavaScript alert box after ignoring the HTML5 validation.

Customised HTML5 messages

As you would hope it is possible to customise the messages that are displayed by the browser with your own text, but this can only be done via JavaScript. You need to check the validity state of the element yourself and set (and clear) the message explicitly:

The block of JavaScript below the form is assigning our custom error message to the checkbox when the page loads. We know that the checkbox is unchecked by default so we need to tell the browser what message to display.

The onchange event handler on the checkbox then toggles the error message. When the checkbox is valid (checked) the message is set to blank which tells the browser that it’s ok for the form to be submitted.

When the checkbox is not checked and the Submit button is clicked an alert is displayed similar to the examples above, but using our text instead of the default.

Here you can see the custom message being displayed in Firefox:

Custom messages can be set in a similar manner for text and other elements, but you will need to check the validity object states (validity.valueMissing | validity.patternMismatch | . ) to determine the current message to display. See the link under References for details.

Separating FORM from function

The previous example was starting to become a bit cluttered with two JavaScript script blocks as well as the onsubmit and onchange event handlers inlined in the HTML.

We can separate the JavaScript code from the HTML and have the required event handlers assigned after the page has loaded using an onload event listener.

Here first is the HTML with all JavaScript removed:

example4 » . > .

field_terms » type=»checkbox» required name=»terms»> I accept the Terms and Conditions

And then the JavaScript to reinstate the event handlers:

The forms behaviour should be unchanged:

While it looks much more complicated, this is a better solution because it allows for the HTML and JavaScript to be maintained separately. The only hooks between them are the id values for the form itself and the checkbox input element. Also gone are any globally defined functions or variables.

The JavaScript can now be moved to a separate file, or converted to a code library allowing for it to be reused with other forms.

The required attribute on checkboxes is supported in Internet Explorer 10 and most/all other browsers except for Safari which currently ignores it.

CSS3 required styles

As we’ve see in other articles the valid/invalid state of a form element can be used to provide visual feedback to the user — displaying a green thumbs up or checkmark for example when the input requirements have been satisfied, or displaying a red outline or warning symbol when they have not.

This is also possible with checkbox elements, just a bit trickier because you can’t really place anything on the inside.

Here’s some sample code to get you started:

The CSS depends of course on how you mark up form fields. In this case we’ve included a label element alongside the checkbox which allows us to reference it using the CSS3 adjacent sibling selector. These styles are all being applied to the label element.

Clicking on the checkbox or the label text will now toggle the checkbox state, and the text will change from red to green. Basically, when the checkbox is happy, the label is happy.

There are also clever ways of styling the label to look like a checkbox and hiding the actual checkbox so you can use your own graphic, font icon or CSS creation:

input[type=»checkbox»]:required < display: none; >input[type=»checkbox»]:required:invalid + label::before < content: "\2610"; padding-right: 0.2em; font-size: 1.6em; color: red ; >input[type=»checkbox»]:required:valid + label::before

In this case we’ve used some UNICODE ‘ballot box’ characters for the on/off state. They are prepended to the label, but actually toggling the checkbox in the background. We know the checkbox is changing because that’s what drives the CSS effect:

The HTML for this example is the same as above.

For more examples like this check out our new article Styling a Yes/No Checklist with CSS.

Did you find any of these examples useful or have any questions? Let us know using the Feedback form below.

References

  • HTML HTML5 Form Validation Examples
  • HTML Validating a checkbox with HTML5
  • JavaScript Preventing Double Form Submission
  • JavaScript Form Validation
  • JavaScript Date and Time
  • JavaScript Password Validation using regular expressions and HTML5
  • JavaScript A simple modal feedback form with no plugins
  • JavaScript Counting words in a text area
  • JavaScript Tweaking the HTML5 Color Input
  • JavaScript Credit Card numbers
  • JavaScript Allowing the user to toggle password INPUT visibility
  • PHP Protecting forms using a CAPTCHA
  • PHP Basic Form Handling in PHP
  • PHP Measuring password strength
  • PHP Creating a CAPTCHA with no Cookies

Источник

Input Checkbox required Property

The required property sets or returns whether a checkbox must be checked before submitting a form. This property reflects the HTML required attribute.

Browser Support

Syntax

Property Values

  • true — The checkbox must be checked before submitting a form
  • false — Default. The checkbox is not a required part of form submission

Technical Details

Return Value: A Boolean, returns true if the checkbox must be checked before submitting a form, otherwise it returns false

More Examples

Example

Set a checkbox to be a required part of form submission:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Javascript вывести многомерный массив
Оцените статью