Validate form using HTML5
- 24-07-2022
- Trung Minh
- 0 Comments
In this article, I will show you how to validate a form with HTML5, this is a pretty simple but very effective way.
In the past we used to validate forms with Javascript, but now you can do it using the attributes that HTML5 has added to the input and select tags. Although it sounds very easy, in reality we still rarely use it, because the interface is not as beautiful as professional validation libraries.
1. Required data entry in HTML5
To require the user to enter data in the input box, we use the require attribute. Now if you intentionally submit the form, it will notify you to enter data in that box.
<form> <input type="text" required /><br /> <input type="submit" value="Submit now" /> </form>
2. Requires entering email address using HTLM5
If you want to force the user to enter a certain cell with the email format, use the input type="email"
tag.
<form> <input type="email" required /> <br /> <input type="submit" value="Submit Now!"> </form>
Alternatively, you can also use the pattern attribute as follows:
<form> <input pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/" required /> <br /> <input type="submit" value="Submit Now!"> </form>
Which way should be used?
In fact, you can use any method, as long as it gives the right result. However, do not use both at the same time because it will easily create conflicts.
3. Request to enter the website URL in HTML5
The input tag is very magical, it has a type attribute with many different categories, including URL types.
To validate the url, we use the following way:
<form> <input type="url" required /> <input type="submit" value="Submit Now!"> </form>
Alternatively, you can also use pattern.
<form> <input type="url" pattern="https?://.+" required /> <input type="submit" value="Submit Now!"> </form>
4. numeric input required in HTML5
The input type="number"
tag will allow the user to enter a number, this is a pretty good method, because it provides us with two more min and max values.
The following example is a data form with a number input required:
<form> <input type="number" required> <input type="submit" value="Submit Now!"> </form>
And here we will limit the two values min and max, you will not be able to enter numbers outside of its range:
<form> <input type="number" min="10" max="20" required> <input type="submit" value="Submit Now!"> </form>
If you want every click to change the value with a jump other than 1 then use the step attribute:
<form> <input type="number" min="10" max="20" step="2" value="16" required> <input type="submit" value="Submit Now!"> </form>
Above are some ways to use HTML5 to validate data from forms. This article is relatively simple, but will also help you grasp some of the basics of HTML5. See you in the next post.