Do I need JavaScript Form validation? - javascript

I'm working on some forms for a Website. Currently I have the usual HTML Browser check (with "required"-tag and patterns and stuff in the inputs), I check the values in a JavaScript before submitting and I do a server-sided check of the data after submitting.
Everything works fine, even if I have only one of them enabled, but it seems a little bit overkill to me, so my question is if I can just leave the Javascript check out? Of course I need to keep the server chek :D
Looking forward to your answers!

You must always validate input at serverside. Javascript is optional and it just to make life of your users easier. Your users get better experience. That's it.

All modern browsers support the HTML5 form field attributes. As you are using those, you may skip the JS validation.

To expand a little on the current answers:
Server side validation is always required, you mentioned that.
HTML and Javascript validation are used for different things.
The HTML required tag can be used to check a form's fields are not blank before a form submission.
Javascript validation allows you to be far more flexible with what you want to validate and when. However, it requires more work because it's not as simple as a required tag.
With Javascript you can do far more. Some examples:
Validation that occurs as soon as a user starts to type
Have the box highlight a different colour
Show an error message
Have a big red cross appear next to invalid fields or a big green one next to valid ones
Spin your page around when the user enters something invalid. (don't actually do that)
etc.
Also note browser support for the required tag.

Related

Logging in to the Netflix website using JavaScript

I'm trying to write a wrapper for the Netflix web page in Qt using QWebEngine so that I can use my remote control to navigate. For those who didn't know, the Netflix website can't even be navigated using the arrow keys...
So, anyway, I have used QWebChannel to inject some JavaScript code into the web page, and can (visually, at least) modify the relevant elements:
document.getElementsByName("email")[0].value = "%1";
document.getElementsByName("password")[0].value = "%2";
document.getElementsByClassName("btn login-button btn-submit btn-small")[0].click();
This actually works (I can see the fields filled with what I provide for %1 and %2, and the button is pressed programmatically), except for one crucial issue: this results in the messages below the input forms telling me "Please enter a valid email." and "Your password must contain between 4 and 60 characters.". These tell me somehow just setting the HTML elements' values doesn't have the same effect as me manually typing in the values. Could someone help me figure out why this doesn't work, and how I can make it work? I would like to restrict myself to plain JavaScript, it seems like a simple enough task to achieve without e.g. jQuery or some other Javascript library.
I understand this is a terrible way to approach the whole Netflix-on-a-HTPC thing, but I don't want to go digging through e.g. Flix2Kodi's Python to figure out what they are doing (which seems to me is a lot more susceptible to bad breakage than the end result I'm aiming for).
The input field for the email uses some sort of HTML5 and ReactJS validation mix.
However it seems like ReactJS validation cant handle the the dynamic value change, so I tried to find a way to deactivate it, which I did not directly, but I guessed that it has to add some sort of event handler to the form so I came up with this:
var validatingForm = document.getElementsByClassName("simple-login-form")[0];
var nonValidatingForm = document.getElementsByClassName("simple-login-form")[0].cloneNode(true);
validatingForm.parentNode.replaceChild(nonValidatingForm, validatingForm);
which gets rid of all event handlers and therefore ReactJS's validation. Now you can set your value using your code:
document.getElementsByName("email")[0].value = "%1";
document.getElementsByClassName("btn login-button btn-submit btn-small")[0].click();
Note that HTML5 is still validating the inputs, so you have to provide an E-Mail Adress, if you want to get rid of that too set the input type to text before changing the value:
document.getElementsByName("email")[0].setAttribute("type", "text");
However the next page after the Button click asks for the password so you'll have to provide it there as I didn't find a way around this.
Buuuuuttt could you not have saved the password in your browser, let it do it's autofill work and fire the click event only?

form values don't pass after I put script links on page

I have a multi-step form for capturing leads and generating potential client estimates. I modified a framework that I found elsewhere on the web. The form looks and works beautifully now, but I need to pass the values from the form through PHP to email. I'm not a stranger to this process, but I believe that something in the Javascript required to make the form beautiful and interactive is voiding the values that should be passing from the form to the email.
What I have done to test (trust me, I hate to bother people, but this is driving me nuts):
I eliminated the fieldsets and any other extra form-formatting, all links to CSS and Javascript. I tested the form and it worked as expected. I took the name in the name="name" field and emailed it to me no problems.
I systematically reconstructed the form until it was complete with fieldsets and CSS. I tested at every step and the form continued to pass the name into the email.
Finally, I added the javascript used for transitions and calculations to the bottom of the page and it no longer performs as expected. It triggers the PHP, but it doesn't redirect as I want it to. and it sends the labels in the email, but doesn't pass the values from the form. If I move the Javascript links to the head, the transitions don't occur making it impossible to navigate to the submit button. Any clues?
Here is the link to the form: http://bigislandwebsitedesign.com/test_form.html
You can follow the links to the various scripts from the source.

Accessibility in javascript form validation

This is an important issue for the blind community which I'm trying to adress. How would I tell blind visitors that the username is taken?
My current set-up is not important but for examples case, I've currently got a Jquery implementation that checks the user input against a php script over ajax, which returns a json which I then display on screen in an error field. Very basic, and beyond the scope of my issue as it is working perfectly.
But if I'm blind, I won't notice that the username Batman is already taken or can't contain spaces, and that my password requires at least 7 characters.
Alternatively, the errors are listed on the error landing page after the form is submitted without javascript- it's chunky but it works. A better more dynamic solution and suport would be optimal.
As a screen reader user I usually just fill out the entire form, submit it, and if it doesn't work I then look for error text. In order to notify a blind user about invalid data before the entire form is submitted take a look at the aria-live="assertive" option scene on the following test page, section d.
http://www.accessibleculture.org/articles/2011/02/aria-alert/
Out of all the test cases section d is the only test that worked for me under firefox 18.0.1 with Jaws 13.0. For some reason the alert option doesn't work. You could use the assertive option to notify the user that something was wrong.

Is it possible for the browser to cache Javascript/DOM changes?

I am developing a form using Javascript for styling that will be used to submit many different things. However, the majority of the time the different things will only be slightly different so it would really benefit users if when you press the Back button on the browser, the form is exactly as you left it before you submitted the form.
Note: This already works when using a normal HTML/Javascript-less form, the question I am asking is how I can retain this functionality when using Javascript to hide/replace input fields etc.
I've tried History.js and HTML5's replaceState() but nothing seems to work. Also if it helps, this will be a private website that requires the latest browser installed so don't feel hesitant to recommend solutions only available in the latest browser releases.
Many thanks!
Update #1: Here's an image better explaining what I need.
Update #2: Okay I managed to crack it perfectly, cross-browser included. I'll post a solution tomorrow after I've had some sleep.
Okay so I went back to the drawing board and tried to figure something out using the tools I already know exist. The case with each browser (usually, haven't tested any non-major browsers) is that when you press the Back button after submitting a form, text input fields are usually populated. I wanted to see if this worked the same with hidden input fields, turns out it does!
So next I set up some Javascript events to listen out for the page load.
if($.browser.mozilla)
{
$(window).on('pageshow', pageManager.init);
}
else
{
$(pageManager.init);
}
This works for Chrome, Firefox and IE9. I haven't tested any other browsers but these are the only browsers that will be used for my private site so it's good enough for me. I'm sure you can set up your own preferred solution for your needs but this is what worked best for me.
Anyway the above code means every time the page loads, pageManager.init() will run. Here's an excerpt of the code I use to check if the Back button was pressed and it's not simply just a page refresh or a first-time visit:
if($('input[name="form_submitted"]').val() != '')
{
// back button was pressed
}
As you can see, it's as simple as checking if your hidden form field contains a value. To actually guarantee a value will be set, make sure to set on submission of your form:
$('#my-form').submit(function()
{
$('input[name="form_submitted"]').val('true');
}
It really is as simple as that. This is one of the best methods I can think of for determining if the Back button of a browser was pressed. Now, to cache all the form values for the visible fields it can be as simple as using JSON.stringify() on the fields and sticking it all in one hidden field which you decode later.
AFAIK, this is generally handled manually. That is, you use hashtags or pushState (with appropriate state object) and either on hash change or on popstate you grab the hash/state, and (re)build your DOM as needed.
(note, I combined two very different scenarios into one there, sorry. if you were only using hash changes, you wouldn't likely be using pushState, as pushState doesn't trigger onhashchange according to MDN.)

Why use a form tag when you're submitting via ajax?

Philosophical question:
Say I've got a web app that requires javascript and a modern browser, so progressive enhancement is not an issue. If my form is being built via javascript, and my data updates are all being done via ajax POSTs & PUTs, is there really any reason to wrap my controls in a form tag? If I'm still going to use the tag, say for semantic or structural reasons, is there any reason to have action and method params that I'm going to ignore? It kind of feels like a hold-over from an earlier era to me.
There is at least one important user-experience feature provided specifically by wrapping inputs inside a form tag:
The enter key will submit the form. In fact, in Mobile Safari, this is how you get the "Go" button to appear on the keyboard.
Without a form wrapping the inputs, there is nothing to submit.
You can of course provide enter-key behavior through a keypress event, but I don't know about if this works for mobile devices. I don't know about you, but I'd rather work with the semantics provided by the browser than have to imitate them with events.
In your case, you would simply provide an onsubmit event handler for the form, which would do your AJAX submit, then return false, canceling the actual submit.
You can simply provide action="" (which means "self"), and method is not required — it defaults to GET.
If you do not need progressive enhancement, you theoretically don't need them.
On the other hand, forms have some cool grouping and semantic effects. Using them, you can group your form elements logically, and make it easier for your scripts to gather the values of certain elements.
For example if you want to ajax-submit some user input, it is always easier to say: "let's take all elements in this form and submit them" than saying "let's take this input, these two selects and these three textareas and submit them". In my experience, it actually helps the developer if form tags are present.
AJAX is great but as JamWaffles (+1 to him) said, using form tags provides a fallback method.
Personally I use form tags, even for things I submit with AJAX because it is syntactically clear and makes it easy to grab all inputs within a specific form. Yes you could do this with a div or whatever too but as I said, using a form is syntactically nice.
Incidentally, screen readers treat the content inside a form differently so there are accessibility issues to be considered whichever way you choose to go. Note that anecdotal evidence suggests that Google considers accessibility in its rankings so if SEO is a concern for you, use a form and do it right.
Summary:
forms OK for MVC, simple web apps, bad for component oriented, rich web apps.
Reason:
forms cannot nest other forms: big limitation for a component-oriented architecture.
Details:
For typical MVC applications, forms are great. In rich, complex web applications using a lot of javascript and AJAX and with a lot of components here and there, I don't like forms. Reason: forms cannot nest another forms. Then if each component renders a form, components cannot nest each other. Too bad. By changing all forms to divs, I can nest them, and whenever I want to grab all parameters in order to pass them to ajax, I just do (with jQuery):
$("#id_of_my_div").find("[name]").serialize();
(or some other filtering)
instead of:
$("#id_of_my_form").serialize();
Though, for sentimental and semantic reasons, I keep naming my divs something_form when they are acting as forms.
Not that I can see. I'm currently building a web application that uses <form>s, but I'm using them so I have a fallback method if the user has JavaScript disabled (an e.preventDefault stops the form posting normally). For your situation, where you're saying the user MUST have JavaScript, a <form> tag isn't necessary, but it might be an idea to keep it anyway in case browser need to do anything with it, or to access it as a sort of class.
In short, no, you don't need to use <form> if you're doing pure AJAX, although leaving it in might an idea if you suddenly decide to create fallback code in the future.
In my opinion: If you use it for semantic reasons, then use it as intended. The action attribute is required (also can be left empty) to be well-formed, also you can separate your URI-s from your js logic, by setting the action attribute, and reading it before the ajax call.
I don't see why you would need to use the form tag here. The only reason to use a form tag (other than to get your markup to validate) is if you are going to have the user "submit" the data using a sumbit input or button tag. If you don't need to do that, then there is no need for the form. However, not sure if it will be considered "valid" markup. If you do use it you can just do <form action=""> as action is the only required attribute of the form tag. However, you do bring up a good point, the future of web applications probably will no longer need the form and traditional submit methodology. Very interesting, and makes me happy. hehe :)

Categories