Node.js server-side form validation with client-side response - javascript

Express-form is a quite powerful validation plugin for node.js/express. However, in the examples and documentation, all the responses are server-side (console.log), which is enough for development, but not quite practical to tell the user what's wrong.
At the moment, I can imagine two different solutions:
Submit the form and redirect back / render the form again with req.body and validation messages attached to add 'error'-classes to wrong fields.
Submit the form using AJAX.
I would prefer option 2, as I don't want to query the database again when rendering 'new'. But I have no idea how to pass the validation results back to the client and add 'error'-classes to input fields.
Any ideas?

I try to validate user input via javascript in the first instance in the browser, and then validate on the server outputting errors in the rendered form (a la rails). Right now I'm using my set of custom validators so I can't point you in the right direction with express-form.
Along with my custom regexes I, sometimes, use the validator npm package, you can also use the validator validations in the browser using plain DOM or some framework.
edit:
working with AJAX validations is quite easy, you receive an object in your request (if you use express.bodyParser() middleware), validate the parameters, if there are some errors you can point at it in your response ex.
{
"errors": {
"foo": "must be a number"
}
}
and:
for (i in answer.errors) {
var target = document.getElementById(i);
target.class = "error";
// here you can also handle the error description
}
If you are using a framework on the browser side, there are plugins or I'm sure it's simple to write one.

Related

custom form control custom client side validation in Kentico

We've created a custom FormEngineUserControl to capture date input using 3 text inputs for day/month/year.
On the server we override the bool IsValid() method which works fine and displays the error message if invalid.
However we want to use client side validation also, we can use a CustomValidator control and assign a ClientValidationFunction to call a JS method however this is not then combined with the server validation function and we end up with two validation messages, one that removes when client validation passes, and one that only disappears when the form is re-submit, basically rendering the client validation useless.
Is there no way to register a client validation method with a custom form control? that will then be combined with the server method and error label etc. ?
This should work pretty much like any other .net user control. How are you preventing further processing if the validator returns false? You might need to set StopProcessing property to true.
There a few similar topics which might address your porblem:
stop execution in Custom validator if it false
Custom validator fires but does not prevent postback
I don't think this is feasible as I'm not sure how you could combine client vs server side validation. You cannot ever disable server side validation. The client side validation is just there for better UX, its not secured by any means. The general idea this is used is that you disable form submission until all fields are verified on the client side. If the validation is the same on the server, you should not see the same error messages because otherwise it wouldn't go pass the client in the first place.
The way you could do this in Kentico is to use some custom js (or better yet some framework/library to help you with validation such as validate.js), give Kentico form some id/class and connect the form validation with your js and have each side (client/server) do its job.

Fail-safe way to validate forms in Javascript/Ajax rather than PHP?

Ok, so currently I handle all HTML form submissions in PHP. I submit the form to a PHP file which:
Checks against a cookie created at page load to prevent CSRF.
Contains a require_once() that handles validation.
Runs other logic.
If any of these steps fail, the user is redirected in PHP to the page they came from with an error message.
How I submit the form:
<form method="post" action="filename.php">
This system is fail-safe; as if anything goes wrong, the user is returned to the page they came from even with Javascript disabled.
So my question is; can I create a fail-safe system using just Ajax (an Ajax request to the server on form submission)? So that I don't need this PHP system at all? Is there a recommended procedure/tutorial for this?
I've avoided this so far as the overhead of having both a PHP form handling system as a fail-safe for potential hackers, as well as Ajax, can take several hours per form.
Just to clarify, I don't require support for users that have Javascript disabled. I just want to make sure my system if fail-safe in that situation. I've had a good look around, but it's proving difficult to find clarification on this.
The short answer for the most part is: no.
It is unwise to consider anything client-side as reliable or fail-safe, this is especially true when it comes to validating user input. A rule of thumb is: never trust the user.
Currently, per the description, your form is being submitted to a PHP script that validates form data. This way is going to be your best line of defense since you have a large amount of control on the data you are working with.
It sounds like you want to cut out the form submission and not force another page load. You can use AJAX to pass form information for validation to your script, but your PHP code is still going to be crucial to the validation process.
Basically you want to make your PHP validation solid. Next, start adding some AJAX calls that pass information from forms to your PHP code, but be prepared to fall back to standard form submission if AJAX is unavailable. If there are no problems with AJAX, you can still submit the data, have PHP do its processing, then return a payload indicating success or failure. Keep in mind though, in this context AJAX is just some sugar for the validation. You are only sweetening the deal by saving yourself having to reload a page and transfer the entire document again.
But remember: it is not reliable, and it is not fail-safe. Server side validation is the light at the end of the tunnel.

Comparison of simple User Regeistration by PHP and Javascript

A simple user registration may be completed by PHP (framework: Codeigniter,etc..) and Javascript.Following is simple flow:
PHP
A registration view with form input(user_name,e-mail,password)
post the data to an controller to validation
-Pass, redirect to a completion view
-Failed, go back to the registration view with some alert strings.
Javascript
A registration html with input text(user_name,e-mail,password)
Validation could be done by Javascript directly before submit; Alert strings could be
generated by Javscript. Even submission could be done by ajax. Then redirect to the
completion page.
I found myself code more javascript less PHP. Even the user registration could be done without the "form" tag,right? I am afraid of some parts I had miss or ignore.
Could someone gives me an simple comparison of good/bad parts about these two methods?
User registration details have to be stored on the server. You can use any language you like there, JavaScript (node.js is the current preferred way to achieve that), Perl (PSGI/Plack), Python (WGSI), C# (ASP.NET), PHP (mod_php), whatever. If you did it entirely with client side JavaScript, then the registration would exist only for a particular browser (which makes it rather pointless for almost anything on the WWW).
You can do a lot of things with client side JavaScript.
You can test if the data enter by the user conforms to the requirements you've set (such as "usernames contain only ascii alphanumeric characters").
You can't stop data that doesn't conform to those requirements being submitted to your server though - everything outside your server is beyond your control. Users can edit your pages in their browser as much as they wish. Client side validation is a convenience to the user (giving feedback without a server round trip and page reload), nothing more.
You can use Ajax instead of an HTML form … but there is no reason to do that. It just adds an unnecessary dependancy on JavaScript. That doesn't mean Ajax can't be useful, you could use it to ask the server if a username was already taken while the user is filling out the rest of the form.

Use javascript to control some html fields of a form before submitting

Before submitting a form, i use javascript code (surrounded in PHP) in order to make locally some controls but sometimes javascript may not be enabled client-side.
The fact is that I have to check by pattern/regex each control of the form for example checking email, phone number,.. format so that user cannot enter anything haphazardly. Therefore, if javascript is not enabled, the form must not be submitted, even if all field are fulfilled out.
Therefore my question is to know if there is a tag or function which allow to perform what i want to?
Thank for your help
JavaScript runs client-side.
That means that users have FULL CONTROL over it.
Then, if they want to disable it, you can't do anything about it.
The only thing you should do is be sure that users with JS disabled will be able to submit the form too.
If you use JS to validate the form, be aware that users have FULL CONTROL over it, so they can send the form if they want, even if your code says that it's invalid.
The right way to do it is:
Be sure users without javascript can send the form
Implement client-side validation for users with javascript activation. This way they will have a better user experience (because can know if the data is invalid immediately) and is less server intensive (your server will have to validate less invalid forms).
ALWAYS validate the submited form server-side. Data coming from a client is always UNTRUSTED, even if you think you have validated it.

AJAX validations in struts 2

Can we do client side validation using AJAX in struts 2 application ?
If yes, then please let me know the procedure.
Answer is right here.
http://struts.apache.org/2.x/docs/ajax-validation.html
even provides prototype example instead of dojo
As Sergio said, you could use this, for example, in a registration form where you have fields like:
Username
E-mail
Password
Repeat Password
You can set up some javascript to validate the form before the user submits it, or better yet, don't enable the submit form until all required fields are complete, avoiding user frustration (you tell him specifically where the error is and how to correct it) and adding another layer of validation to it.
In this case you can pre-validate Username and E-mail against the server to see they are not taken yet. You can do something like this (in jQuery, from memory):
$("#email").change(function(e) {
var $elem = $(this);
var val = $elem.val();
if (!val) {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
} else if (!/^[a-z0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i.test(val)) {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
} else {
$.getJSON("isEmailAvailable.php", {email:val}, function(result){
if (result.available) {
myMarkField($elem, "valid");
myValidateForm("myForm");
} else {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
}
});
}
});
Where isEmailAvailable.php should return something like { available: true }
AJAX is the mechanism by which you could invoke the server-side validation. The "J" in AJAX stands for Javascript.
You would typically make use of AJAX (and hence Javascript) to invoke some sort server-side validation that would be inappropriate for client-side validation. For example, the validation of a zip code against a table of acceptable values.
How would you do this? You use JS for client-side programming (including validation), it has nothing to do with the server side.
Additionally: server-side-validation via the client-side JS would be a bad idea, as all your validation code would be exposed to the user.
If your going to do server-side input validation then what do you need to use JavaScript for?
I'll make the assumption that you are using PHP on the server-side in which case you'll want to validate it there instead of making another unnesicary request.
If you want to use AJAX to do some server-side validation (and you'r using JQuery) this should at least get you started:
function validate(fieldName)
{
$.get('/validation.php',
{'value' : fieldName.value, 'name' : fieldName.name},
function(data, textStatus)
{
if(data)
{
fieldName.style.class = 'validFormInput';
}
else
{
fieldName.style.class = 'invalidFormInput';
}
})
}
I'm no JS/JQuery expert and I didn't test this so it's just to get you started.
I think you need to read a bit about AJAX.
I recommend this link: http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
I think it's simple and easy to understand.
Basically you have server and client side code. JavaScript (client side) can invoke a URL using Ajax(Asynchronous JavaScript And XML) witch is very similar to invoke any other URL using a browser. The main difference is that there is no page reload.
Your JavaScript will need to be waiting for the reply in order to handle it (in your example show or hide an error message).
Basically it allows you to execute some code at the server an update your page without a page refresh.
In short, the AJAX application architecture enables the client (i.e. a piece of JavaScript running in a web browser) to actively ask for information from a server. Most often, the JavaScript client will use the received information to update small portions of the browser's document using the DOM.
Also, the JavaScript client code can do some obvious validation of e.g. a form to be sent to a server (as shown so nicely by Danita's answer).
The server can be anything. It may just return a plain xhtml file, or may respond to the request by calling a complex PHP script that generates a response. Heck, it may even be a dedicated mobile device entirely implemented in bare C. As long as it implements the http protocol the client's request was transmitted in. This might be JavaScript. Improbable but true.
So Yes: it can be done using 'server-side' JavaScript, if you have a server running JavaScript. But No: that's not probable.
And Yes: you apparently need to read upon AJAX. (I'm not a webdesigner, and even I seem to know more than you ;) Don't leave it that way!)

Categories

Resources