JavaScript Validation Functions Tutorial

104 6
    • 1). Create two HTML pages, one that we'll put our test form in and another page that we'll use as a simple destination for our form. We'll refer to the page with the form as form.html, and the other page as dest.html. You can add whatever content you like to either of these; we'll assume you at least have the standard HTML boilerplate in place (i.e. <html> and <body> tags).

    • 2). Create a standard HTML form and give it an onsubmit attribute like so:

      <form onsubmit="return isValid();" action="dest.html">

      ...

      </form>

      Later, we'll create the isValid() JavaScript function, and by setting the action to dest.html, we can tell whether or not the JavaScript actually prevented the form from submitting.

    • 3). Add some elements to the form so we have something to work with. To keep things simple for now, we'll use two regular text fields, and only require data in one of them:

      <form onsubmit="return isValid();" action="dest.html">

      Name (Required): <input type="text" name="nameData" /><br />

      Nickname (Optional): <input type="text" name="nickNameData" /><br />

      <input type="submit" value="Submit" />

      </form>

      Note that we used both "id" and "name" for those fields. We'll refer to the fields by their id in the JavaScript later; in a real application, you'd need the name attribute as well, since that's what would get passed along in your request.

    • 4). Add a script block at the bottom of the form.html page (i.e. above your closing body tag), with the following JavaScript code in it:

      <script type="text/javascript">

      function isValid() {

      var nameDataField = document.getElementById('nameData');

      var valid = (nameDataField.value.length > 0);

      return valid;

      }

      </script>

      We get the value of the nameData field and check its length. If the length is greater than 0--there's something in the field--we return true; otherwise, we return false. Since we configured the form with onsubmit="return isValid();", the event will only continue (i.e. actually send the request to the action URL) if isValid returns true.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.