A complete guide To HTML Forms

Article


author small image Siva Kishore G
Posted : 02 June 2022
Modified : 21 Sep 2022
Beginner Developers

HTML Forms

Forms are a core part of any website. Primarily, they are used to record users' input and save / process as per required. Usages such as Contact Us, Get A Quote, Subscribe, Login, Register, Survey etc.

Using these forms, one can send emails, login to a bank account, send/receive money, update info etc. So it's crucial to know how a html form works, what security issues it poses and how to safeguard against any attack that may occur.

Anatomy of a Form

As mentioned above, a typical form is a HTML element which is composed of various input elements (learn more) and a submit button. We can choose the way the form submit's the data to the server.

  1. <!-- Simple Form Example -->
    <form>
      <label for="firstName">Enter First Name</label>
      <input type="text" placeholder="Enter name" name="first_name" id="firstName"  />
      <button type="submit">Submit</button>
    </form>
    • Method : GET
    • Action : CURRENT_PAGE
    • Security : Insecure
    • Usage : Pagination, Search etc
  2. <form method="POST" action="/some-route">
    • Method : POST
    • Action : Route Specified in the action attribute
    • Security : Secure
    • enctype : application/x-www-form-urlencoded
    • Usage : Login, Signup

    When the form is of type "POST", it assumes a default enctype of "application/x-www-form-urlencoded". Other possibilities of enctypes are

    1. multipart/form-data (File Uploads)

      This type of encryption type is suitable for forms that handle file uploads since the default enctype will is not suitable. The payload is wrapped in an object which consists of parts, literally!. Each part has a key and each key has headers and content (binary - base64).

      The final object that's sent will have an encoding of "UTF-8", mediaType : "multipart/form-data", boundary, mimeType and contentLength. No separate encoding is necessary here because of the unique boundary and the content already being converted to base 64.

    2. text/plain (Unreliable)

      In reality there is no encryption here. Only the spaces are converted but everything else (including special characters) are kept the same and sent to the server. This is to be used only for testing purposes.

    3. application/json (Abandoned)

      The W3C has drafted quite a few proposals for it's implementation but it never happened and is stuck in a "recommendation" stage. It's unclear if it will be included in future because the HTML group has no intention maintaining it.

  3.  <form action="/some-page" autocomplete="on">

    Autocomplete, the name says it all. Browsers will auto fill the values based on previous form fills. For example, in google chrome, you can have your credit card data saved and it will be supplied automatically at your next checkout.

    Even though this is a very handy feature but poses some risk. For example, anyone else using your personal computer may be able to autofill all your details. So it's always better to keep this autocomplete feature off when handling sensitive transactions like online banking.

  4. <form action="/submit-form" novalidate>

    Forms can be validated using the "required" attribute on input elements. They will check if the user has entered input and if it's the input type. For example, the form will not be submitted if a proper email address is not supplied into the input element with attribute type="email".

    This functionality can be overridden using the novalidate attribute supplied to the form tag. The form can be submitted with whatever values entered into the input fields regardless of the required attribute on the input field.

  5. <form action="/submit-form" onsubmit="submitForm(event)">

    Many times we would want to submit the form without the page reload (default functionality). For this, we can use the onsubmit attribute and pass a function with event as it's parameter. In this function use event.preventDefault() to stop the page reloading.

    This method allows us to create custom input validation or modify the data before sending it to the server. For example, consider a register form. We would want to see if the password supplied is secure enough viz;at least 8 characters, special characters, at least one uppercase letter etc.

    See my easy form submission tutorial to learn how to submit form dynamically.

Secure your Forms

Forms pose major security issues unless handled correctly. So it's very important for every developer out there to know what they are and how to protect against them. Let's discuss one by one.

  • SSL

    This is a no brainer. SSL / HTTPS encrypts all the data transfer from & to the web server. So a MITM (man-in-the-middle) attack is useless. In MITM, the hacker sniffs the web traffic between the client (victim's computer) and router. This person doesn't need to be connected to the victim's router. For better understanding, think of watching a highway from a distance and tracking the road traffic.

    While sniffing the traffic, the hacker can capture the HTTP packets, reorder it and deduce the message by which the hacker can know what the victim is doing, what message he/she is sending and which website they are on.

    But, if the user is on a secure website (HTTPS), then the traffic is all encrypted. Even though the hacker has the HTTP packets, he/she cannot use them as they are just gibberish which can only be decoded by the server.

  • ssl
  • SQL Injection

    Typically, the website saves the form inputs to a database and most likely it's done on mySQL. The queries used on server side looks like this INSERT INTO table_name (column_1,column_2) VALUES ('data_from_website','data_from_website') learn more

    If the data from the website is simply passed to the database without cleaning, it can create havoc. The user can add his/her own SQL code inside the message and submit. It can cause the table to just drop, get sensitive data etc. So, it's always a good idea to sanitize the inputs before saving to the database.

    Now the question arises, should I be sanitizing the input values at the front end or the backend or both? I would say, both! We can choose different ways of sanitizing the inputs at the front end (in-browser). Use javascript functions such as encodeURI, btoa which converts any string to base64 and in my opinion it's the easiest, regex and replace etc.

  • CSRF (Cross Site Request Forgery)

    This is usually done by sending an email to the victims. This email has a link and upon clicking, the link opens the target website and does actions which the user never intended. For example, the link may look something like this. https://some-website.com/account?change_password=12345.

    Now, the hacker has successfully changed the password of the unsuspecting user. If this is a banking website, you can imagine how disastrous it could be. This can be prevented by supplying a server generated token every time, the user loads the website. This way, the server checks if the incoming request has this token present and is valid. To secure it even more, these tokens generated expires in stipulated time which is usually 2-5 minutes.

  • Stop the spam

    Online forms are targets of many companies that solicit their products (spam) and believe it or not, it works even though the conversion rate is very low. At the end of the day, it's just a nuisance for most of us. But it's a real menace if you are using third party mail service like "sendgrid" or "AWS SES" etc, as your email reputation goes down with the number of spam you receive.

    Spammers typically use bots that go from website to website and submit forms programmatically. They exploit legit softwares like "Selenium" or "Puppeteer". There are even some blacklisted softwares available in the black market (TOR networks) which can be purchased and can be more successful causing more damage. Look into "XRUMER" (This is for educational purposes only). Beware! Soliciting websites can carry punitive damages.

    Few techniques exists to ward off these spam attempts such as honeypot, recaptcha, solve the problem etc. These are aimed at verifying if the form is submitted by a real human being or not. Out of these, recaptcha is very famous. it's basically solving a puzzle before the form is submitted.

JQuery for form submission

JQuery has very handy syntaxes for processing the form data. Usually, this is done by stopping the default behavior of the form (event.preventDefault()) and invoking $.ajax, $.post or $.get to submit form dynamically. This will allow adding our own headers, submission methods, authorization type etc.

// Show Loading overlay
$.ajax({
  url: 'https://my-example-website.com/submit-form',
  type: 'post',
  data: {
    name : 'first name',
    email : 'email@gmail.com'
  },
  success: function(result){
    // Hide loading overlay
    console.log("Result",result)
  },
  error: function(err){
    // Hide loading overlay
    console.log("Error",err)
  }
})

Human Perception

Let's discuss how we, the humans perceive the forms. it's a known fact that forms are abandoned if they are too long. Short forms has highest success rate in converting. If long forms are absolutely necessary then we can do it in steps. Checkout this login implementation which follows a step method while keeping the user engaged all through out the end.

There are other techniques like providing a score or depicting a level upon every question asked. This kind of form is more suitable for surveys. Try this example

How is your website doing?

(1/13) How often do you update your website
Once a day
Once a week
Once a month
Once a year
Never
(2/13) How old is your domain
Purchased recently
< 1 year
2-5 years
10+ years
(3/13) Do you have google my business established?
Yes
No
Dont know
(4/13) Is your website mobile optimized?
Yes
No
Dont know
(5/13) Is your website secure? (HTTPS)
Yes
No
(6/13) Does your website has structured data?
Yes
No
Dont Know
(7/13) Does your website follow silo structure?
Yes
No
Dont Know
(8/13) How much content do you have on each page
350 words +
150 words
Less than 150 words
(9/13) Do you do email marketing campaigns ?
Never
Once a week
Once a month
(10/13) How many social media accounts established? (facebook,twitter,intagram etc)
2 or less
2-5
5 +
(11/13) How often do you update your social media accounts?
Never
Once a week
Once a month
Once a year
(12/13) How many reviews does your business have in google?
50 +
10 +
< 10
none
(13/13) How fast does your website load?
Under 3 seconds
3 - 5 seconds
5 - 8 seconds
Dont know

If you like this tool and want to add it to your website, please contact us

Conclusion

As we discussed about how forms are an integral part of any website, it is your duty as a developer to keep yourself updated with these security techniques and there is no better place than this.



Post a comment

I promise, I keep it clean *

Comments

Alert SVG Cookie Consent

This website uses cookies and similar technologies, to enhance your browsing experience and provide personalized recommendations. By continuing to use our website, you agree to our Privacy policy.