Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML HTML Forms Choosing Options Checkboxes

Elise St Hilaire
Elise St Hilaire
13,358 Points

Required input fields

What if I don't want the user to be able to submit the form unless they fill out their name, email and password? How do I make parts of my form required?

Chris Davis
Chris Davis
16,280 Points

Just add required to you input element

<label for="username">Name:</label>
<input type="text" id="username" name="username" required>

2 Answers

andren
andren
28,558 Points

The simplest way of marking an input as required (and the only pure HTML way) is to simply add the "required" attribute to the input element like this:

<label for="name">Name:</label>
<input type="text" id="name" name="user_name" required>

<label for="mail">Email:</label>
 <input type="email" id="mail" name="user_email" required>

<label for="password">Password:</label>
<input type="password" id="password" name="user_password" required>

The caveat to the required attribute is that it only works if the browser you use support it. All relatively modern browsers do, but you can't always be sure your users will be using a modern browser.

The other thing worth mentioning is that while this will warn users when they forget to fill something out it won't stop malicious users from submitting the form empty. As with all client side checking it can be disabled by the client. So you will still have to have checks on the server that receives data from the form, in order to verify that data was actually entered even if you mark fields as required.

Elise St Hilaire
Elise St Hilaire
13,358 Points

Thank you for the answers! I appreciate the explanation that further action may need to be taken outside of the HTML to ensure that the form is not submitted empty.