HTML5 form validation

The purpose of introducing HTML5 validation is to notify a user that a page contains some mandatory information that needs to be filled or corrects the users for any errors using the browser's built-in processing. We should take advantage of all the capabilities and knowledge that the browser has, to catch errors within a form, before sending it to the server. Also, we need not bother about the time and expense of a network round-trip or getting a response from the server about some stupid error.

New <input> attributes such as required and pattern used in combination with CSS pseudo-class selectors make it easier to write the checks and display feedback to the user. There are also other advanced validation techniques that allow you to use JavaScript to set custom validity rules and messages or to determine whether an element is invalid and why.

Before we go deeper into HTML5 validations, let us see the difference when the client-side validation is performed using JavaScript and how we can validate using HTML5 <form> controls. Here, in the following instance, we are validating a simple textbox which is mandatory to be filled in by the user.

Code 1 – validating a textbox using JavaScript

The following code will validate a textbox using JavaScript:

<head>
<script>
  function validateField()
  {
    var x=document.forms["Field"]["fname"].value;
    if (x==null || x==""){
      alert("Please enter your name");
      return false;
    }
  }
</script>
</head>
<body>
  <form name="Field" action="#" onsubmit="validateField()"method= "post">
  First name: <input type= "text" name= "fname">
  <input type= "submit" value= "Submit">
</form>
</body>

The output of the preceding code will be as shown in the following screenshot:

Code 1 – validating a textbox using JavaScript

Code 2 – validating a textbox using HTML5 <form> controls

The following code will validate a textbox using HTML5:

<head>
<script>
</script>
</head>
<body>
  <form name= "Field" action= "#">
  First name: <input type= "text" name= "fname" required>
  <input type= "submit" value= "Submit">
</form>
</body>

The output of the preceding code will be as shown in the following screenshot:

Code 2 – validating a textbox using HTML5 <form> controls

In the preceding two code examples, we saw how the <script> part in the first code was replaced by a single attribute of the HTML5 <form> control in the second code, which not only reduced the lines of code, but also removed the scope of JavaScript.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.96.5