DEV Community

ishar19
ishar19

Posted on

The curious case of HTML forms

Forms are an inevitable part of any application if we are making an application that’s interactive and relies on user inputs.
And as the sensitivity of data grows, handling forms becomes critical.
So let’s talk about HTML forms.

<form action="https://www.something.com" method="get">
        <label><input type="text" placeholder="text"/></label>
        <button type="submit" >Submit</button>
    </form>
Enter fullscreen mode Exit fullscreen mode

A basic structure of HTML form
The action attribute of the FORM element defines where to send the form data, and the method attribute specifies the HTTP method(i.e, GET, POST) for sending the form data.
The URL inside the action would probably be an API endpoint but if it is an URL and method is get, chances are you would be redirected to the page. Go on, try running above code and you will be redirected to https://www.something.com which (funny enough) is an actual website with “something”, quite literally.

One less harmful use of this could be instead of using links, usage of form buttons for redirection so user wont know where they are going to be redirected by just hovering.(PS:- this is not best a11y(accessibility) practice but there could be some use cases)

Major risk of doing forms like this inside HTML could make your website vulnerable to an attack called XSS (Cross Site Scripting) which are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user.

One of the biggest e-commerce website E-bay fell prey to this kind of attack numerous of times in the past and to this day XSS attacks are quite common.

(Explanation of XSS is quite outside of the scope of this article, for further reading, you can visit

https://brightsec.com/blog/xss-attack/)

Tip: Always verify the URL of the page if you are putting in any personal information.

Above Example was provided to point out the importance of validation of any type of user input taken in a website.

Validation

HTML provides a way to validate the data provided to it’s input elements

<form>
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" required><br>
  <label for="age">Age:</label><br>
  <input type="number" id="age" name="age" required>
</form>
Enter fullscreen mode Exit fullscreen mode

Above code will validate that first name provided is in text format and age should be a number and both are required if user wants to submit the form.

<input type="text" id="uname" name="uname" pattern="[a-zA-Z0-9]+" minlength="4" maxlength="10">
Enter fullscreen mode Exit fullscreen mode

For example, above code will validate that text only contains letters from a-z A-Z and from 0-9, hence invalidating other inputs. This may seem like a valid solution and to an extent it is, but writing strong reg-ex could be very tiresome and another issue could be posting data directly to backend using methods like curl or wget.

Hence validating data sent on backend is also important and there are tools like joi and strip-js for that.

Okay, this was all about validating but how do we submit?

Well you can submit your form using a submit type button and execute some code using onsubmit event provided with forms.

onsubmit

<form action="https://api.server.com" method="post" onsubmit="someFunction()">
        <label><input type="text" placeholder="text"/></label>
        <button type="submit" >Submit</button>
    </form>
Enter fullscreen mode Exit fullscreen mode

When users submit the form using the submit button, first the function provided to onsubmit executes and if everything goes well, the form is submitted.
But one very irritating part you would notice is that page will reload everytime user tries to submit and hence creating a very bad user experience.

So how do we solve it?

Using the event object,
onsubmit gives us access to an event object, which can be used to used to do various things like preventing default action, accessing data on which the event was occurred and much more.

<script>
    function someFunction(e){
        e.preventDefault();
    }
</script>

<form action="https://api.server.com" method="post" onsubmit="someFunction(e)">
        <label><input type="text" placeholder="text"/></label>
        <button type="submit" >Submit</button>
    </form>
Enter fullscreen mode Exit fullscreen mode

This will prevent the page from reloading but here’s the interesting thing, it also prevents the form from submitting, because contrary to a beginner misconception, what preventDefault does is that it prevents the default behaviour of an event rather than just preventing the reload and submitting is also a default behaviour of onsubmit.

So what do we do,

use the best programming language for your rescue, JavaScript

Take the formData and the action URL and post it to your server using The Fetch API

async function handleFormSubmit(event) {
    event.preventDefault();

    const form = event.currentTarget;
    const url = form.action;

    try {
        const formData = new FormData(form);
        const responseData = await postFormDataAsJson({ url, formData });

        console.log({ responseData });
    } catch (error) {
        console.error(error);
    }
}
Enter fullscreen mode Exit fullscreen mode

(According to MDN, The Fetch API provides an interface for fetching resources (including across the network), more about Fetch and APIs later someday)

Above code might look unfamiliar if you are new to Javascript, you can go read about Fetch, try-catch and every other thing on The MDN.

By no means this article can act like a comprehensive guide to forms and submission, this was just to show some pitfalls and ways to avoid it. Why validation is important and why learning about fetch and ways to validate data is important.

Conclusion: Developers should really pay attention about forms and user inputs and it’s validation.
How javascript solves an essential problem by letting us access the Fetch API (which by the way again, contrary to mass-misconception is not a part of javascript rather a browser API.)

But thats all functionality, what about styling, after all it also has to look good

Well, CSS provides a lot of ways to style a form and in some amazing ways which we will look in some another article, till then Ciao.

Top comments (1)

Collapse
 
ayushmangarg2003 profile image
Ayushman Garg

Amazing Blog