Maths sum for javascript validation on form - javascript

Trying to create a very piece of validation to prevent spammers. I want a field with a label saying 'What's 2 + 7?' so the Javascript needs to know the result and pass the validation. I'm struggling to write this, would it be something along the lines of:
var valid = '';
var required = ' is required';
var sum = $('form #sum').val();
if (sum == '9') {
valid += '<p>An answer is' + required + '</p>';
}

It is hard to tell exactly what's needed without looking at more code.
A simple question like this may very well work if it is generated server side and it is a lot better for accessibility than captchas. In order to be effective the question and answer should also be randomly selected.
You may chose to include a pre-submit client side validation for usability purposes, but since spam bots ignore JavaScript, it is useless to prevent them, unless you do something really complicated.
A bonus tip off topic: Your JQuery selector is inefficient. When using an id-selector you will never need to include its parent.

Client side validation via Javascript is not going to do much to guard against spammers. Most spammers will have bots that don't even parse Javascript.
The only way to do this reliably is to handle it server side.
I would recommend trying something like Recaptcha: http://www.google.com/recaptcha

Ok so this is not going to answer your question per se but I want to suggest that you don't do this. Creating these spam preventions mechanisms is actually very complicated and your idea isn't really going to work if a spammer really wants to come after your site. I would suggest you look into a service called recaptcha. It is free, easy to set up and the information entered by users is put to use digitizing old books.

As I wrote in comments, you could prevent the bots from posting your data with just a javascript by itself. Let me explain how you could do it:
You could set initially the wrong or empty action for your form and later, with the help of javascript, set it to the correct one if the answer on the 'sum' was correct. Or even without the request for 'sum' as most of the spam-bots do not run js.
You could insert a hidden field named 'passed' with false initial
value of it. Again, based on form interaction, you could set it to
true and later check the data from the form (the value of this
hidden field) on the server.
The last method, which I prefer in most cases, is to encode html
code of your form with, for example, base64 and use your javascript
to convert it back to HTML code. As soon as bots do not run js, they
will not even know that you have a form on the page. The good part here is that you do not have to ask a person to enter something else in the form.
All these methods can be bypassed by a person interested in spamming on your website. He could check the final data sent to the server and create the set of the same requests to your server. That is why you need some server-side support in order to prevent you form even from manually crafted spam requests.

Related

Need advise. How to validate forms with AJAX and not to create excess load on server?

Well, hello everybody, I faced with a big problem which I can't solve.
So, here is it: I need validation, but I have my own expectations towards it.
So, what I do:
Here everything goes right as I suppose...
I get the values from fields (e-mail(text input), username(text
input), sex(radio btns), birth date(select lists),
password&repeat_password(password inputs).
Then I handle and validate those values. For example: I check if email is not empty, if it fits the pattern, if birth date is right and real, if password fits needed limitations. Another words, here I validate all params without AJAX, just using custom JS.
After validation, I get the responses from each field with messagies of validation result and the result(Boolean) itself.
HERE'S THE PROBLEM COMES UP
So, as I have results of validation, now I need to check if EMAIL is UNIQUE and if USERNAME if UNIQUE. This ofcs should be performed with AJAX, but IMPORTANT: I shouldn't perform request to server to check email if there were some problems with email before. If its OK, I send it. Same with username field.
AND FINALLY, validation is boundaried on onsubmit event, so I want to check email, username with no AJAX, then validate them on being UNIQUE if there were no errors before with them and then IF ALL fields are correctly validate, only at that case I send form, in other occasion I would like to use event.preventDefault() .
So, due to AJAX works in async way, I can't use event.preventDefault inside it, so that's first problem. Also I cant return anything from ajax callback to let system find out if there were any validation issues or not.
I am not asking for a solutions, I am not crazy, I understand that there is a lot to think about, BUT I want some of matured gyes helped me with advise, how to validate forms correctly using AJAX? How to divide code on blocks in validation and make it reusable, using async AJAX?? Pls, I'm struggling a lot. I've already written a lot of code to validate fields with no ajax, and I dont understand how to relate them with ajax, send the form if everything OK.
Can u share your expiriance in validating forms, how do u usually do it? How have u learnt how to validate forms? AND WHAT ARE BEST PRACTISES OF VALIDATING FORMS WITH AJAX?
When it reaches form validation, there are a few things you should keep in mind:
1. Importance of the transmitted information;
2. How reliable it needs to be;
3. How many requests you are going to have;
4. How much information your form is going to hold;
In my honest opinion, I would use Javascript/Ajax for quick and more accurate paths in your form. For example:
1. Validating date fields are in correct format;
2. Validating ages are matching your requisitions;
3. Validating a gender was selected (BTW it is gender you are looking for, not sex);
etc...
Anything that needs to be correct and secure on your website (specially passwords and emails, etc), if you want to validate such you should do it on your server. Always!
Now, if you form is too long, you can do a step by step registration, instead of all in one. You can keep the progress saved in the session (server side) and maybe use a cookie to inform your site that they started the registration before (for this you can use javascript);
NOTE: You should inform your user you are using cookies as it is mandatory due to GDPR :)
Both validations help making the user journey smoother. There are things you should defo use as Js validation for quick response and making sure user is aware of some mistakes before they submit the form.
Server validation is safer for the sensible data that you need to make sure is correct as user as no say in it.
But it really depends on what you are trying to achieve and how many resources you have available to you.
Ajax form validation overalls
Form validation
Hope it helped clear some things up! :)
use this
https://reactiveraven.github.io/jqBootstrapValidation/
this will help you to set all validation on client side, once fullfilled, it will hit the 'validation success call method' and then go to ajax,
You can also set custom validation like, minlength, maxlength,should contain, maxcheck, mincheck, email/phone formats , etc
revert if any problem

What are some ways to make it harder for the client to manipulate the DOM?

I am going to be processing a lot of form data from the client using Ajax. Right now, my way of validating input is to add a 'validate' class to each form control that needs to be checked. When the user enters information (or submits the form) the script looks at the input of each control with that class and verifies its contents before moving to the next tab (or sending it to the server). The issue, of course, is that a user can easily remove the class and the item wouldn't be looked at.
While I will of course be validating the input on the server-side (client data can never be trusted!), a lot of the user-side content generation [new inputs, dynamic forms, removing/adding validate classes, etc.] depends on people not tinkering with the classes. While I know that the client can ultimately do whatever they want, what are some ways to make this process difficult for the client to manipulate?
So far I have thought about:
Running a script at the beginning of the page load that grabs all the HTML inputs with the 'validate' class and stores them in a variable. When the user submits the data or moves to the next tab, instead of looking at the elements with the class 'validate', I instead look to validate the data compared to the contents of the variable.
Adding data-validate HTML attributes to each input and doing the same thing as above (running a script and grabbing the inputs that need validation before the client has time to tinker with the settings)
Is there anything else that can be done? I am a little hesitant to use the above approaches because there may be new, dynamically generated form elements that need to be added/removed to the list; and this + grabbing the data at the beginning of the page load could cause a little unnecessary overhead.
"While I know that the client can ultimately do whatever they want..."
You just answered your question. If that's your starting point, why are you trying to make it harder? Is it worth my while to actually try to hack your site? If it is, I don't care that it's harder. Also, how hard can it be? Are you going to make it so hard to figure out the JavaScript that the next developer who looks at this code also won't be able to figure out what's going on?
Also, you're adding more code. Have you ever written code without bugs? I haven't. So, guaranteed, there are going to be bugs in this thing. So, in the off chance that 1 in a million users might try doing something bad, you'll end up stopping lots of legitimate users who get errors when they're using the site like they should.
Client side checking is ONLY meant to be nice to the end user, to give them immediate feedback. Period.
Might not be the answer you like, but it is the answer. :)
Edit: One last comment. Let's say you did make it REALLY hard. Would you then not do server side checking? Would you say to your boss, "Oh, we made it pretty hard to hack on the client side. They still can. We just made it hard. So no need to do server side checks." Of course not. So, if you're doing server side checks no matter what, you don't gain anything from trying to obfuscate on the client side.

Isn't input sanitisation with JavaScript pointless?

Background:
I've been searching for a way to sanitise some form inputs with JavaScript to prevent the form being submitted if it contains characters that aren't whitelisted.
I've come up with this based off a brilliant Stack Overflow answer
function allowSubmission(string) {
return string == string.replace(/[^\w\s]/gi, 'X');
}
var s1 = 'simple string';
var s2 = 'alert(0);';
var s3 = '<nasty>string';
console.log(allowSubmission(s1)); //true
console.log(allowSubmission(s2)); //false
console.log(allowSubmission(s3)); //false
Problem
But doesn't this just mean a potential attacker can turn off JavaScript and submit whatever the hell they like? Or simply edit the JavaScript on the fly and overwrite the validation method to just return true.
Question
SO... Isn't input sanitisation with JavaScript pointless?
This only means you should always validate and sanitize your input server-side. Regardless of whether it's checked in front-end as well.
Doing this in JavaScript can help you avoid unnecessary requests hitting your backend and increasing the load as well as improve the user experience but they should not be treated as a means of security.
It's pointless, when treated like a line of defence. In general, its use serves many purposes.
But doesn't this just mean a potential attacker can turn off javascript and submit whatever the hell they like? Or simply edit the javascript on the fly and overwrite the validation method to just return true.
Yep, but that doesn't make javascript validation pointless.
The purpose of javascript validation is not to sanitize input for the server. That job must be handled by the server.
The purpose of javascript validation is to make the user interface more responsive for the user. JavaScript validation allows the user to know when they made a mistake without having to wait for a potentially slow server response. It can also reduce the overall load on the server.
Client-side JavaScript should never be used as the only means of sanitizing input, it can be used to assist the server, but in the end the server must be able to correctly handle invalid input.
Input sanitization is not done for security, but for usability. You should give feedback to the user that he inputs bad characters as soon as possible (on each keystroke), not after he submits the form and the response comes back from the server.
For security you MUST validate anything coming from the client on the server. There is no way around it.

Best practice for handling errors in forms submitted via ajax?

I'm wondering what is considered best practice for dealing with forms submitted via ajax. Specifically, I'm wondering what is the best way to handle a form which contains errors.
I see two possible options upon submitting a form with errors:
A. The server returns a JSON document of name value pairs of fields names / error messages. This would then need to be processed client-side and the form would need to be altered by prefixing each field with it's error message and changing the form's styling (adding an error class to the fields for example).
OR
B. The server simply returns a new HTML fragment containing the form with error messages and styles pre-applied. No need to process anything client-side except swap-out the form.
To me option B seems like the easier/quicker option but I can't help but feel that it isn't 'best practice'. Is there pros/cons for either method?
Separation of logic is a huge one here I reckon.
As a project grows, you generally have a front-end team and a back-end team. Imagine the website gets a huge makeover but the logic stays the same. Option B is harder to change the style when the layout is enforced server side.
The application logic (which is this case is server side validation) should be separate from the presentation layer (which is this case is the html/css rendered by the browser).
But at the end of the day, we get paid to produce results so if your not trying to win an academy award for best quality code, and you got bills to pay, just get it done the quickest way.
I'd go with the first option.
The second option just increases the load on the server ... which you always want to avoid. Plus, I feel that if the styling was done on the server-end, the your website isn't exactly modular ... all styling should be done on the front end only.
This is sort of an opinion question but there are a few objective things to say about the topic. Your first option, the pure JSON choice is best used for apps that focus on speed an keeping HTTP requests as small as possible.
The other option, to process your form server-side then return the new form through AJAX doesn't seem to have too many advantages to me. If you're going that route then why bother with AJAX at all? Why not just do a regular form post to the server?
I usually prefer a front end validation and server-side verification. This way you can avoid a JSON call at all if things aren't valid but just in case someone sneaks something in there the server-side code will verify.
I would establish a JSON scheme for validation on the front end. Just basic stuff like what you're checking for on each field, which fields are optional, etc... That gets baked into every page with a form on it. Then let your front end devs pre-validate to avoid unnecessary calls in whatever way makes the most sense to them.
Pre-built errors isn't against any best practice I'm aware of and it's not a terrible way to go (people tend to throw the UI manual of style out the window when it comes to forms anyway), but sometimes you'll want to give more specifics or different errors for different problems.
Always aim for having your cake and eating it too, IMO.

Checkbox Captcha

I'm initiating my first start-up. I can't stand attempting to read captchas when signing up for websites, don't want my users to. I looked for alternatives, and I found the checkbox captcha. How is this done, using JavaScript to load a checkbox, and validate it with the same code as would normally be used to make a sign up form?
Thanks.
I looked at the example linked from the article you posted. At first glance, it seems like this can be easily bypassed.
The checkbox captcha works on the basis that spam-bots don't parse or use JavaScript code embedded in webpages. Because of this, they will not find the captcha checkbox element within the form it is searching, and therefore will not send a post value for the checkbox along with the form, and on the server side, you would reject the form if the checkbox value wasn't sent.
The problem with this is:
The checkbox name is always the same (gasp_checkbox)
A bot could easily be "trained" to detect this javascript on your page and act accordingly
Even if you output a random name and value that must be used for the checkbox, it could still be detected
The outcome of those 3 problems means that this is much easier to break than image captchas or other methods. All a bot has to do when they submit your form is add: gasp_checkbox=on to their HTTP request.
That said, if you implement this for yourself on your own site, it is unlikely that any bots will able to get past it because its use is not widespread.
You could make it more secure by doing the following:
Generate unique name/value pairs for the checkbox on the server side, and output those values in obfuscated javascript to the client
Serve the script away from your form, preferably in an external javascript file that is generated by a script.
Verify that the values sent for the checkbox match a pair that was previously generated, and not used before.
If you do those things, I think you could have an effective checkbox captcha. If someone does catch on to it on your site, it may still be trivial to defeat, even with the above safeguards in place, but it may take a while, and still be effective for you most of the time.

Categories