ASP.NET validation using AJAX without update panels - javascript

I'm looking for a way to use custom ASP.NET validators to validate input, without using UpdatePanels, and without a full postback.
The validators do several things - not just length/regex, but some other non-standard stuff as well.
Javascript is required for our users, so I don't have to worry about normal users who have javascript turned off.
I see several options, but none are ideal:
1) Suck it up and use UpdatePanels. I'm in the "UpdatePanels are evil" group, so I'd prefer not to do this.
2) Without using validation controls, manually validate the fields by passing the values to a PageMethod static method, via jQuery or any other AJAX framework. This would require client and server coding each time I needed to use a validator.
3) Use jQuery (or any other javascript framework) validation for client validation, then if they somehow get by that, have server-code validation controls for full postback. This would require all of the validation rules to be written in javascript as well as C#. I don't care about the full failed postback at this point, because the javascript validation would catch real users who weren't trying to screw me over.
Is there alternative out there for using real CustomValidator controls, with partial postback, C# code only, for validating input without UpdatePanels and without a lot of redundant javascript?
Thanks

I'd use a mixture of 2 and 3.
First- Server side validation will exist regardless...
So I would make the fields that require simple validation logic javascript based (numbers, text, string lengths, string certain formats etc) with no ajax callbacks, and then use callbacks to the server where business rules or otherwise more complex validation needs to occur, so that complex rules are only coded once.
If you had to pick between either a very fast response (or no delay...js only), or valid data, I'd expect that valid data would win...So using 2 and 3 together hopefully will give you a faster response, but without compromising valid data.
Ajax callbacks to a generic handler etc should be a bit quicker than an UpdatePanel anyway as far less data would be being transferred...

Honestly, I think 2 is a good option. CustomValidator or not, you'll write the same server code to do the validation. You can do all the validation code in C#, and just write JS to call your validation method, which could be a PageMethod or a separate ashx. And really, you could probably write one JS function that takes parameters to make the AJAX call pretty easily.

Related

pass javascript variable to ajax

I am working on a site with many forms . Most of the forms will be submitted via jquery AJAX.
I have implemented recaptcha for security but the client does not like it as the words are sometimes difficult to read.
As an alternate I am looking at honeytrap method for less important forms. As I understand In this method I keep a field in the form hidden from normal users via CSS. So legitimate users will leave the field blank while a bot will fill it .
Now my question is since I am using jQuery AJAX for form submission, instead of hidden field if form , can't I just pass an extra variable (along with form field variables) from javascript to AJAX. (like var secretword = 1) AJAX will check this variable( if secretword == 1 ) and if it is empty(bot will not use javascript to sumbit form so var will be empty) then the form will not be submitted.For legitimate users javascript function will add "1" value to the variable.Is my method as secure as honeytrap?
NOTE: Website does not work without javascript so need not go into what happens if javascript is disabled.
Please provide me your valuable advice on this.
You're really over-thinking this.
If you only do legitimate submission via AJAX, make the form's action attribute wrong, and you've effectively accomplished what your proposed solution does: Anybody directly submitting the form without JS will have their submission ignored.
This obviously won't deter anybody from figuring out where you AJAX submissions are going and just spamming that endpoint directly, but neither will your proposed secretword=1 solution or a traditional hidden field.

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.

Advanced Form Validation in JavaScript

I'm already familiar with how to use onSubmit to evaluate form content against RegEx to ensure it meets static parameters for acceptable content. What I'm wondering is if there is a way to further provide validation against a MySQL database, such as if you want to make sure an e-mail address hasn't been used yet before submitting a form and having to re-load the field data back into the proper places for correction.
Unless you sent all the valid email addresses to the client (you wouldn't) then you're going to have to do some sort of server roundtripping to validate the field, which is equivalent to submitting the form. But using AJAX you can fully validate the form without the user experience being compromised; to them it will look like any other client-side validation. There are JQuery plugins to help make AJAX-based validation easier to code, but it isn't too hard to roll one up yourself.
you have to use a serverside language for that: php, perl, python... as javascript (client-side technology) cannot communicate with a mysql server (serverside technology) directly.
In javascript you could use the AJAX methodology if you want to avoid the full page refresh. Try using jquery, (a javascript library that take care of crossbrowser issues and simplifies greatly rich interaction programming) and its $.ajax() function. This has been made really easy through the use of the jquery form plugin.
Most examples of this kind of validation use some kind of asynchronous request back to the server to do the lookup in the database. Either by using XMLHttpRequest or some other Ajax style method.
I'd recommend creating a small URL end-point that you can make a quick HTTP request to sending the email address to check. It can return either true or false in a simple JSON response.

Matching password in .Net validate by JavaScript?

I have two textbox in Asp.Net: first for password and second is for a matching password.
How can I validate whether user entered different value in both textboxes through JavaScript at client side?
Have you considered the CompareValidator control for this?
It's what the CompareValidator was designed for.
edit - added
If you just want the javascript and want to do it completely in javascript, here's an example:
http://www.willmaster.com/library/manage-forms/ensuring-two-form-fields-have-identical-information.php
However, the CompareValidator takes care of generating the javascript for you (as long as client side validation is turned on), so in my opinion (and it IS just an opinion) you're making it harder on yourself by writing the javascript yourself.
The simplest js for this would be
if(document.getElementById('password1').value != document.getElementById('password2').value){
// they do not match
}
But if you are using .NET, you might want to take the advice to use a CompareValidator.

Favorite Web Form Validation Technique

What is everyone's favorite way to sanitize user data?
I've been using Javascript, but have recently required something more secure (people can turn it off, after all), so I was looking at Flex, but thought I'd ask the community what they thought.
NEVER NEVER NEVER use javascript or any other client-side technology for the only validation. You can use client-side validation to save some load on your server or make your app seem more responsive by showing the error sooner when validation fails, but you should always validate using server-side code.
Personally, I like the ASP.Net validation controls because it gives you the benefit of client-side validation with security of server-side, without having to write your logic twice. Of course, the stock controls are pretty bare, but you can extend them.
Validation should ALWAYS be done server-side. Doing it client-side, in addition, is fine.
How you do it depends on what your app is written in. Any language should be able to handle validation; the logic used is what matters, not the language.
It also depends on what you're doing with the data you're given. Putting it in a URL or storing it in a SQL database requires two very different kinds of sanitization. If at all possible, white-list valid values--don't black-list invalid values. Someone will always be able to come up with a new mal-input you hadn't considered.
Depending on the requirements of your project you may or may not want to implement client-side validation. However, server-side validation should ALWAYS be implemented. I prefer to white-list appropriate inputs and values as opposed to black-listing invalid data because this ensures that no one will ever slip something by that I failed to consider.
always use server side validation at the very least
use regular expressions
PHP Example:
preg_match('/^[\w][\w\,\-\.]*\#[\w]+[\w\-\.]*$/', $_GET['email'], $matches);
if (count($matches) > 0) {
$_GET['email'] = $matches[0];
} else {
die('invalid email address');
}
It's recommended to use both server- and client-side validation.
I use JQuery for client side validation.

Categories