What JavaScript library to use for client-side form checking? - javascript

Over the years, I've dabbled in plain JavaScript a little, but have not yet used any JavaScript/AJAX libraries. For some new stuff I'm working on, I would like to use a js library to do client-side form validation, and want to know which would be best for that. By best, my criteria would be: quick and easy to learn, small footprint, compatible with all popular browsers.
Edit: Thanks for the ASP suggestions, but they're not relevant to me. Sorry I didn't originally mention it, but the server is a Linux box running Apache and PHP. As I know I should, I plan to do server side validation of the input, but want the client side validation to improve the users' experience and to avoid as much as possible having the server reject invalid inputs.
Edit 2: Sorry I didn't reply for months! Other priorities came up and diverted me from this. I ended up doing my own validation routines - in addition to the good points made in some of the answers, some of the items I'm validating are rarely used in other applications and I couldn't find a library with that sort of validation included.

You could use jQuery and it's Validation plugin.

I don't use libraries myself, but dived into some (like prototype, (yui-)ext, the seemingly omnipresent jquery, mootools) to learn from them and extract some of the functions or patterns they offer. The libraries (aka 'frameworks') contain a lot of functionallity I never need, so I wrote my own subset of functions. Form checking is pretty difficult to standardize (except perhaps for things like phone numbers or e-mail address fields), so I don't think a framework would help there either. My advice would be to check if one of the libraries offer the functionallity you look for, and/or use/rewrite/copy the functions you can use from them. For most open source libraries it is possible to download the uncompressed source.
It needs to be said (by the way and perhaps well known allready) that client side form checking is regarded insufficient. You'll have to check the input server side too.

Before AJAX Libraries I used Validation.JS by Matthew "Matt" Frank.
The basic idea is that you include a JS file and then add attributes to your INPUT statement.
Example:
<input name="start-date" type="text"
display-name="Start Date" date="MM/YYYY" required="#getRequired()" />
Field will be validated as a date in MM/YYYY style. Any error message displayed will refer to the field as "Start Date". The "#" prefix will cause the getRequired() function to be evaluated at run-time.
A variety of things are provided as standard (Currency, Date, Phone, ZIP, Min/Max value, Max length, etc), and there is a keystroke filter; alternatively you can roll your own - most easily by just defining a Regular Expression for the field, but you can add Javascript Functions to be called to make the validation.
There are pseudo events for handlers to catch before/after field and form.
In additional to Attributes in the INPUT statement, validation actions can be applied to the field by JS:
// Set field background when in error state
document.MyForm["INVALID-COLOR"]="yellow";
// Show error messages on field blur
document.MyForm["SUPPRESS-ONCHANGE-MESSAGE"]=true;
document.MyForm.MyField.REQUIRED = true;
document.MyForm.MyField.DisplayName="Password";
Validation.JS is 28K (uncompressed)
I've had a bit of a trawl around to try to find an HTML file you can easily get to with details, but I can't fine one standalone that I can link to.
The source code is here:
http://code.google.com/p/javascript-form-validation/source/browse/#svn/trunk
and the DOCs are in the HTML files - but you can't view those as HTML, you have to download them and then view them, as far as I can make out

I do most new stuff in ASP.NET with AJAX, so I use the ASP.NET validators with the AJAX extenders, and they work great. However, if you are not into ASP.NET this isn't going to help you.
Most major JavaScript frameworks (jQuery, YUI, Prototype, etc) have validation capabilities, so you could consider them. But depending on your needs, you might regard it as overkill.
Previously (in ASP Classic) I used my own validation script which was only 6KB; I obviously don't now because I like the consistency and polish offered by these frameworks, but YMMV.

Related

HTML textarea spellcheck: How to tell if user makes spelling errors

I have a textarea that is defined thus:
<textarea spellcheck="true"></textarea>
When users type, spelling mistakes are highlighted to them (using a red underline, for my browser). Is there any way (using jQuery) to check whether there are spelling mistakes before a user submits the form?
This is what I want to achieve:
Form input textarea: [Typing some text in thsi box] [submit]
Before the user clicks submit, I would like a listener to "catch" the fact that "thsi" was spelled incorrectly and prompt the user. Is there any way to do this via the html5 spellcheck method, or do I have to use a custom javascript function for the spellchecking and listening?
A quick search brought up this jQuery plug-in that seems to do exactly what you want and it uses the Google spell-checking API https://code.google.com/p/jquery-spellchecker/wiki/Documentation
There is also Typo.js https://github.com/cfinke/Typo.js, which is a client-side based library. It does not use any API, instead it uses Hunspell-style dictionaries and it is only available for American English "EN_US".
If you don't want to use a plug-in or an existing code snippet, you can build your own by sending an ajax request to check the typed text against a service provider (Google in this case).
you can use jquery plugin for checking spelling.
i hope it helps you, thanks.
JavaScript SpellCheck
http://www.javascriptspellcheck.com/
If you have to build it natively you might consider building a Trie datastructure for this
check this Trie reference 1
Trie reference 2
Hope this helps
You have different ways to achieve it, it depends if your spelling has to be focused on a subject (like medical word spelling) or is it general.
Create yourself a dictionary (not the best choice and too long to make)
make a query to online dictionaries like google
try Jspell Evolution (the installation is a little annoying but once done it works very well Jspell Evolution website
you can look at typo.js typo.js article
Yesterday I found this article that is 10 times better than the others :
Article for javascript spell check locales where you can also have spelling for other languages/locales and not only english locale.

Javascript library to manage translation forms

Is anybody aware of any javascript tool (compatible with jQuery, tinymce or any other clientside library) able to manage the following requirements?
I need to show translation forms in which every field (either input or textarea) could contain some segment variables or code sections (mostly HTML).
For example:
"Hello {{firstname}}, this is your personal page."
or
"You improved your personal score of <strong>{{n}} points</strong>."
Of course I obtain these segments from a template parser and I need to show them to a set of translators that will perform localization towards many languages. I know that in many cases I can (and should!) avoid variables and code inside translation segments, but in many other cases I really can't.
The problem is: I would like to manage coherence about variables and code directly on the browser (I trust my translators but a bit more of UI/UX help is always a good thing!).
A nice approach could be providing the set of variables and code tags, ready to be inserted by means of a single click (in order to avoid mispelled variables or incorrect code syntax) and a bit of pre-submit validation to be sure everything was inserted.
I've seen this approach in other websites, such as Facebook or Freelancer.com (who have the power and the ability to reimplement the whole thing from scratch!).
Do you know about any almost-ready tool/library for this purpose?
Thank you all in advance for any suggestion.
If you are asking for a library to translate text - here is Google Translate API: https://developers.google.com/translate/?csw=1
If you are asking for a library which can take user input, perform validation, and insert into the DOM - then Jquery has everything you need.
If you are asking for something else, let me know and I'll edit my question.

Input validation check

In my website I have a forum, and I want to avoid cross site scripting. Do you know a good input validation script?
There are two ways to avoid Cross Site Scripting.
Filter the inputs by the users
(mainly script tags and html tags)
both at client side as well as on
server side.
Display the contents as
Html entities to avoid Cross Site
Scripting. Ofcourse if you want to show some
of the tags, go for option one.
Otherwise option two is more
reliable.
You can use regular expressions to filter the data both on client side as well as on server side.
I've always relied on the OWASP PHP filters: http://www.owasp.org/index.php/OWASP_PHP_Filters As you can tell from the name, they're server-side (JavaScript or HTML5 validation is only useful for assisting the user) and OWASP (the Open Web Application Security Project) is a non-profit organisation.
It depends on where do you want to write out the data. For example you need different filter when you write the text into an input field and when you write it simply into the html body, between two tags.
You should implement different filters for the different data types on server side. I suggest you should filter the text when it's printed out, and not when the user sends it to you(of course it's not about sql injections and other server side tricks), because (as I mentioned above) the type of the filter you should use is depends on where the data is printed out.
If you want to write a really simple forum, then it's enough to write only one filter, wich simply removes all html tags from the text before it's printed out. Beware, it's not good for advanced functions, for example edit comments, when you prefill a form for the user, or if the users can use any html tag in their comments, etc.
Simple. Make sure you escape the HTML from your input object before using it. This way, the data sent will be treated as raw text. The way to do this will be to pass the input through some parser before embedding the data in your page (or working with it somehow).
I agree with anand that there are two major ways to avoid XSS: validation on input and escaping on output. For validating form input, tie into Django's Form Validation Framework: http://code.google.com/appengine/articles/djangoforms.html
Here are some code samples for sanitizing on output within a Django templating. Instead of this:
Welcome, {{ firstname }}!
Do this:
Welcome, {{ firstname|escape }}!
This is from this very good blog post: http://startupsecurity.info/blog/2008/10/28/avoid-xss-on-google-app-engine/
Server Side
http://www.php.net/manual/en/function.html-entity-decode.php
http://www.php.net/manual/en/function.addslashes.php
http://www.php.net/manual/en/function.stripslashes.php
Check more string functions you need to validate
Client Side
http://www.position-relative.net/creation/formValidator/
better to write your own jquery code, in future it may help you
You have two option for validation. for non-sensitive data client side JavaScript may be use.
in JavaScript, you can write simple function for validating your data.
for sensitive data, you should be use server side scripting like, php,jsp,asp,asp.net etc.
may this will help you.

Add spell check to my website

I have an asp-based website which I would like to add spell checking capabilities to the textarea elements on the page. Most of the pages are generated from an engine, though I can add JavaScript to them. So my preferred solution is a JavaScript-based one. I have tried JavaScriptSpellCheck and it works okay, though I would like to see what some of my other options may be. I also found spellchecker.net but at $3500 for a server license it seems excessive.
Spell checking can be in a separate window and must support multiple languages (the more the better). Ultimately I would like to send the spell check object a collection or delimited string of textarea names or id's (preferably names as they already exist in the pages) and have it spell check all of them, updating the text as spelling is corrected.
Check out using Google's api for this: http://www.asp101.com/articles/jeremy/googlespell/default.asp
Here is a free, open source Javascript library for spell checking that I authored:
https://github.com/LPology/Javascript-PHP-Spell-Checker
There's a link to a live demo at the top. It's designed to have the feel of a spell checker in a desktop word processor. I wrote it after being dissatisified with these same options.
To use, just include the JS and CSS files into your page, and then add this:
var checker = new sc.SpellChecker(
button: 'spellcheck_button', // opens the spell checker when clicked
textInput: 'text_box', // HTML field containing the text to spell check
action: '/spellcheck.php' // URL of the server side script
);
It includes a PHP script for spell checking, but it could be ported to another language fairly easily as long as it returns the correct JSON response.
If I were you, I'd look into something like aspell - this is used as one of the supported spellchecking backends in TinyMCE. Personally, I use pspell because it's integrated into PHP.
EDIT
There's an aspell integration here that has a PHP or a Perl/CGI version; might be worth checking out.
If I am not wrong, Firefox's English dictionary for spell checking takes around 800KB of data.
If you like to do everything in JavaScript -- for a full-featured spell checking engine, it means you need to load that 800KB data in every page load. It's really not a good idea.
So, instead of doing that in JavaScript, send the data to the server with AJAX, check it server side, and return it back; that's the best way.
Well this is quite old question, but my answer might help people who are looking for latest options on this question.
"JavaScript SpellCheck" is the industry leading spellchecker plugin for javascript. It allows the developer to easily add and control spellchecking in almost any HTML environment. You can install it in about 5 minutes by copying a folder into your website.
http://www.javascriptspellcheck.com/
Also support multiple languages - http://www.javascriptspellcheck.com/Internationalization_Demo
I might be a bit late on the answer to this question. I found a solution a long while ago. You must have a spell checker installed on your browser first. Then create a bookmark with the following code as the link.
javascript:document.body.contentEditable='true'; document.designMode='on'; void 0

Where do you record validation rules for form data in a web application?

Say you have a web form with some fields that you want to validate to be only some subset of alphanumeric, a minimum or maximum length etc.
You can validate in the client with javascript, you can post the data back to the server and report back to the user, either via ajax or not. You could have the validation rules in the database and push back error messages to the user that way.
Or any combination of all of the above.
If you want a single place to keep validation rules for web application user data that persist to a database, what are some best practices, patterns or general good advice for doing so?
[edit]
I have edited the question title to better reflect my actual question! Some great answers so far btw.
all of the above:
client-side validation is more convenient for the user
but you can't trust the client so the code-behind should also validate
similarly the database can't trust that you validated so validate there too
EDIT: i see that you've edited the question to ask for a single point of specification for validation rules. This is called a "Data Dictionary" (DD), and is a Good Thing to have and use to generate validation rules in the different layers. Most systems don't, however, so don't feel bad if you never get around to building such a thing ;-)
One possible/simple design for a DD for a modern 3-tier system might just include - along with the usual max-size/min-size/datatype info - a Javascript expression/function field, C# assembly/class/method field(s), and a sql expression field. The javascript could be slotted into the client-side validation, the C# info could be used for a reflection load/call for server-side validation, and the sql expression could be used for database validation.
But while this is all good in theory, I don't know of any real-world systems that actually do this in practice [though it "sounds" like a Good Idea].
If you do, let us know how it goes!
To answer the actual question:
First of all it isn't allways the case that the databse restriction matches client side restrictions. So it would probably be a bad idea to limit yourself to only validate based on database constraints.
But then again, you do want the databse constraints to be reflected in your datamodel. So a first approximation would probably be to defins some small set of perdicates that is mappeble to both check constraints, system language and javascript.
Either that or you just take care to kepp the three representations in the same place so you remember to keep them in sync when changeing something.
But suppose you do want another set of restrictions used in a particular context where the domain model isn't restrictive enough, or maybe it's data that isn't in the model at all. It would probably be a good idea if you could use the same framwork used to defin model restriction to define other kinds of restrictions.
Maybe the way to go is to define a small managable DSL for perdicates describing the restriction. Then you produce "compilers" that parses this DSL and provides the representation you need.
The "DSL" doesn't have to be that fancy, simple string and int validation isn't that much of a problem. RegEx validation could be a problem if your database doesn't support it though. You can probably design this DSL as just a set of classes or what your system language provides that can be combined into expressions with simple boolean algebra.
To keep validation rules in one place I use only server-side validation. To make it more user-friendly I just make an asynchronous post request to the server, and server returns error informations in JSON format, like:
{ "fieldName1" : "error description",
"fieldName2" : "another error description" };
Form is being submitted if the server returned an empty object, otherwise I can use information from the server to display errors. It works much like these sign-up forms that check if your login is taken before you even submit the form, with two key differences: request is being sent onsubmit, and sends all field values (except input type="file").
If JavaScript validation didn't work for any reason, regular server-side validation scenario (page reload with error informations) takes place, using the same server-side script.
This solution isn't as responsive as pure client-side validation (needs time to send/receive data between client and server), but is quite simple, and you don't need to "translate" validation rules to JavaScript.
Always validate every input server-side. You don't know that their client supports javascript "properly", or that they aren't spoofing their http requests and bypassing your javascript entirely.
I'd suggest not limiting your checks to one location though - additional checks within the javascript make things more responsive for your users.
As others have said, you need to validate on the server side for security and data-integrity reasons, and validating on the client-side will improve the user experience, since users will have a chance to fix their mistakes sooner.
It seemed the question was asking more about how do you define the validations so every place that validates is in sync. I would recommend defining your validation rules in one place, such as an XML file, or something, and having a framework that reads that file, and generates javascript functions to validate on the client. It can then use the same rules to validate on the server.
This way, if you ever need to change a rule, you have one place to go.
As noted by others you have to do validation at the Database, Client, and Server tiers. You were asking for a single place to hold validation so all of these are in sync.
One approach used by several web development frameworks (including CakePHP )
Is to organize your code into Model, View, Controller objects.
You would put all your data code including validation in the model layer (comments for database table structure or stored procedures if needed).
Next, In this Model define a regular expression for each field for your validation (along with generic max-size, min-size, required fields).
Finally, use this regular expression in to validate in javascript (view) and in on the server form processing code (Controller).
If the regex isn't sufficient - ie you have to check the database to see if a username is available, you can define a validation method on the model use it directly in your form processing code and then call it from javascript using ajax and a little validation page.
I'll put in a plug for starting with a good framework so you don't have to wire all this up yourself.
Client-side validation for good, responsive user interfaces
Server-side validation because client-side code can be bypassed or modified and so can't be trusted
Database validation if you have multiple apps feeding into one db. It's important here as then a change to validation is automatically propagated to all apps and you don't lose data consistency.
We try to keep get our validation done before it ever hits the database server, especially for our applications which are facing the public internet. If you don't do validation before the data hits the database, you put your database at risk for SQL-injection attacks. We validation through a mixture of javascript and code-behinds.
A good data validation solution could make use of XML Schema based datatypes definition, then both client and server would reuse the types as they would both need to executing it. Worth noting, Backbase Ajax Framework implement client-side user input validation based on XML Schema data types (built-in and user-defined ones)
In the past, I've used XSLT for validation. We'd create an XML doc of the values and run it against XSLT. The XSLT was built of XPath "rules." The resulting XML doc was composed of a list of broken rules and the fields that broke them.
We were able to:
store the rules in a relational DB
generate the XSLT from the DB
use the XSLT on the client
use the XSLT on the server
use the raw rules in the DB

Categories

Resources