Do not use javascript for validations

This one will be widely accepted. The problem with it is that it’s so obvious that the question is asked here and there.

Javascript is not secure

I repeat : javascript is not secure. Your code is readable and it can be modified by anyone. It is great when you want to do a bookmarklet. It is not so great when you want to have a hard as a rock web application.

Example, you want to validate that a manually entered date is less than today. The javascript code for it is not complex.

[source:javascript]
function validateDate(theDate) {
var now = new Date();
return (theDate < now);
}
[/source]

But anyone could override the function to always return true and all the dates that he enters would be good. This is bad.

Always validate on the server-side

Whenever you have to validate something in your web application, use the server-side. I know, it is redundant and long to do but you must do it. Someone once said that you must consider every input from the user has evil.I prefer the word dirty. Users sometimes don’t want to be evil to a web application but they are. And sometimes, users want to be evil.

If you have little time to implement an application, just do the server-side validations.

You must consider javascript validations as “pretty” validations. It validates things but it just to make your application prettier. In facts, it helps you with usability and it simplifies the life of the users of your application.

The “cheap return” method

To avoid to write a lot of code on the server-side for validations, I would suggest you a simple method that will help you code faster. It is called the cheap return method.

  1. You do all the validations on the client-side in javascript.
  2. You do all the validations on the server-side but if it fails, you display a generic page to the users that says that it has failed.
  3. You pretend to have done it completly on the client-side and server-side.
  4. You spend the rest of your time watching the ceiling.

The idea behind that is that if all javascript validations have passed, the users must have done something between the client-side and server-side. So, he is responsible of that error.

I don’t really like it either…

Commentaires

  1. Frank April 25 2007 at 16:53:24

    Dan,

    I would tend to agree with you (in fact, you’re the one who woke me up about this issue some time ago).

    However, I don’t think that javascript validations are just meant to be “prettier”. They should also be used to give a break to your server and thus improve your overal application performance.

    I’d say that at least 85% (speculating…) of web users have javascript turn on at all time. The vast majority of them let the javascript run as intended. Of course, you are right when you say that you must ALSO validate on the server to protect your app from attacks. I also see server validations as “serious validations” and client side validation as “bonus validations”. The thing is, bonus validations will do the trick almost everytime. This means less work for your web server

  2. SchizoDuckie April 25 2007 at 18:39:04

    I’ve solved this in a very neat way:

    I submit my forms with a callback using pork.iframe and return a
    JSON object with a piece of javascript in it.

    The serverside does all the validations javascript would do and
    just prevents the form from saving it’s data.

    Consider this example:
    $val)
    {
    if($Profile->hasProperty($key))
    {
    $Profile->$key = $val;
    }
    }
    $Profile->Save();
    $_TPL[’js’]->status = “Your profile has been saved!”; // set a div’s innerhtml
    $_TPL[’js’]->script .= “document.location=’{$_TPL[’baseDir’]}Profile’”; // execute this js
    $_TPL[’js’]->display(); // die() with a new JSON object with above properties
    }
    ?>

    You can find this in action at my site www.cyclotracker.com

  3. SchizoDuckie April 25 2007 at 18:40:06

    Something went wrong with the example

    $Profile = new Profile();
    if(FormValidator::validate($Profile)) // if it doesnt, it dies with a JSON object with script that adds messages
    {
    foreach($_POST as $key=>$val)
    {
    if($Profile->hasProperty($key))
    {
    $Profile->$key = $val;
    }
    }
    $Profile->Save();
    $_TPL[’js’]->status = “Your profile has been saved!”; // set a div’s innerhtml
    $_TPL[’js’]->script .= “document.location=’{$_TPL[’baseDir’]}Profile’”; // execute this js
    $_TPL[’js’]->display(); // die() with a new JSON object with above properties
    }

  4. James April 26 2007 at 00:16:14

    Dan, Frank

    I agree to both of you, and to summarize what I have just read that is to do both server and client side validation. That could be a double work :(

  5. Binny V A April 26 2007 at 00:40:28

    I always do both client side and server side validations. Client side validations are easier for the user - they could see the error without reload. And server side is more secure. So, I have the best of both worlds.

    The only disadvantage is it takes more time.

  6. Craig Francis April 26 2007 at 03:41:43

    Generally I find that doing both JS and Server Side validation is a waste of programming time.

    The main problem I face is that I am rarely the only programmer on a project, and its quite often that I will see the validation rules for the server side validation get out of date and un-tested… purely because the some programmers/testers see the JS working, and don’t think about the second level.

    Personally I think that the speed of the JS does not outweigh the cost of development, the code duplication, or the problems with future maintenance.

    However, I have seen server side code which also generates the JavaScript validation code… this seems to get around the problem, but it hits my second issue with JS validation… if there is a problem with the code, its possible that the browser won’t handle it correctly, and the user will not be able to submit the form… they will press the ’submit’ button multiple times, and it will do nothing… and they will get annoyed.

    I know that with proper unobtrusive JavaScript this can be avoided… but Internet Explorer does strange things at times, so it cannot be guaranteed.

  7. Timo Stamm April 26 2007 at 05:12:21

    Please tell me this is a joke.

    Of course it is insecure to rely on JS for validation. But not because someone could modify your site, but rather because YOUR SERVER IS STILL WIDE OPEN TO ABUSE if your script accepts form data without validating them.

  8. Frank April 26 2007 at 05:43:29

    Ehh, I think you’re just playing with words… or you are simply missing something. The point of the author is that JS validations are insecure since you can override them and get to the server with dirty form data.

    I thought it was quite obvious… maybe because I didn’t stop reading after the first few words? Yeah I guess it helps

  9. Craig Francis April 26 2007 at 05:54:38

    Also, not sure if this will help anyone, but it does prove on how easy it is to bypass JS validation… goto:

    http://www.craigfrancis.co.uk/features/tools/formFaker/

    And enter the URL for this page (javascriptkata) in the first text field, then press the ‘Get Form’ button.

    When the page re-loads, it shows you the form config so you can edit the fields/values… and below that, a form so you can submit this data to the given action URL.

  10. Binny V A April 26 2007 at 07:02:13

    @Craig Francis
    Its much easier than that - if you have ‘Web Developer’ extension, just disable the Javascript using that extension. Then your data will bypass JS validation.

  11. Timo Stamm April 26 2007 at 10:44:54

    Frank: I did read the article, thank you, and I don’t think reading it again will fix it’s flaws.

    “Do not use javascript for validations” is a bad recommendation. Actually, using JS for validation is good, because it can provide instant feedback to the user.

    It’s wrong to say JS is insecure. Contrary to what is stated in the article, it is NOT possible for anyone to modify scripts on your site – unless your site has serious XSS vulnerabilities or your server is insecure.

    It is possible, on the other hand, to access your server side script without even using a web browser. If you don’t know the HTTP protocol, please don’t try writing “hard as a rock web applications”.

  12. Craig Francis April 26 2007 at 11:27:55

    @Binny V A
    It is very true that the web developer extension can help with most situations, its a wonderful tool (like firebug) which I cannot develop without… however quite allot of poorly coded websites will require the use of JavaScript to submit (especially when there isn’t a single line text field to press [enter] in).

    @Timo Stamm
    While it is true that JavaScript has security features to prevent third party websites from bypassing security (same domain restrictions etc)… I think Dan was referring to the actual users bypassing the JavaScript validation… for example someone creating an account with a single letter password, when the validation requires 6 letters.

  13. Dan (maintainer of Javascript Kata) April 26 2007 at 11:44:27

    @Timo
    I just wanted to awake web developers that javascript is not secure. That’s why I’ve written the title that way.

    I surely do all the validations on the client-side but it should always be done after the server-side validations. A lot of developers forget it.

    In fact, you should always secure your site thinking that anyone could bypass all your javascript validations or directly send a request to the server WITHOUT going through the page that validates client-side.

    I really thought everyone know it but I was wrong… as usual…

    PROTECT YOUR OWN CODE FROM YOUR OWN CODE!

  14. Timo Stamm April 26 2007 at 12:32:17

    Dan, glad to hear you are aware of this. No, not everyone is – I understand this is the reason you wrote the article in the first place. I didn’t mean to be rude, but your point seemed less than clear to me.

    I’m still irritated by the claim that JS is not secure – it’s like saying C is insecure because it doesn’t feature a built-in String representation.

  15. Dan (maintainer of Javascript Kata) April 26 2007 at 12:39:39

    @Timo
    When I say that Javascript is not secure, I really mean it. Remember the validateDate() function in the post? To bypass it, anyone could write this in the address bar of their browser :

    javascript:validateDate = function(theDate) { return true; }
    

    and it the function would be overwritten to always return true.

    That’s what I mean when I say that it’s not secure.

  16. BK April 26 2007 at 16:43:53

    If you want a real world example, simply look here:
    http://www.boingboing.net/2005/07/28/microsoft_genuine_ad.html

  17. All in a days work… April 27 2007 at 06:24:08

    […] Do not use javascript for validations Javascript is not secure. Your code is readable and it can be modified by anyone. It is great when you want to do a bookmarklet. It is not so great when you want to have a hard as a rock web application. (tags: JavaScript Date/Time) […]

  18. […] no doubt, and I use it heavily. But the following article has given me a lot to think about. Do not use javascript for validations | Javascript Kata Please share your […]

  19. Nater Kane May 18 2007 at 15:18:11

    The idea of client-side validation being secure is something that isn’t even worth discussing…
    the benefits of the double check are very simple and with many common/popular server-side languages, the logic for front and back end should be very similar.
    1) if the user fails clientside validation, you save having to make a round trip to the server, and the user may be shown a descriptive and contextual error/response message so they may correct the non-valid data. if they pass clientside validation, only then the data is passed to the server for the second validation.
    2) isn’t that good enough of a reason? a quality and humane user experience should come a close second to application security.

  20. Rick Fletcher May 24 2007 at 00:49:06

    I’m with Nater, completely. Your headline shout have read “Do not rely on javascript…” instead of “Do not use javascript…”

  21. BK May 24 2007 at 08:08:41

    Subtilities of the language! :P

  22. Dan (maintainer of Javascript Kata) May 24 2007 at 08:25:57

    @Rick and Nater
    I know it should have been “Do not rely…” but the problem is that title has low-impact. I’ve seen a lot of people using javascript as the only validation and I wanted to catch these people.

    So, I won’t change the title and I hope that they will understand what I mean.

Post a comment

Comments are moderated and innapropriate ones won't be approved. Please respect this public space.