I need to build multiple business forms with basic validations.
Example field types:
required field
date (datepicker)
time (timepicker)
email
money
integer number (+ optional min/max value)
decimal number (specify precision)
phone number
social security number
zip code
credit card number
masked text (+ optional regex validation)
field with server side validation
etc.
Is there a lightweight library or framework that provides some or most of those field types out of the box as well as the ability to create custom fields with validations?
You can these. I would think that a server-side validation is good too in addition to front-end validation
Use HTML5 (frontend) native validation
https://github.com/Zhouzi/GentleForm
PHP some people have created their own class they shared Easiest Form validation library for PHP?
JQuery validation https://jqueryvalidation.org/
I recommand you to use vuito, since it's template-based and isomorphic you can share your validations between front and back-end super easily. The package weight less than 1.3kB.
Related
I have a complex form with some fields that are generated on the fly using JS/jQuery.
The problem with this generation on the fly is the complexity to validate this fields on the server side. I don't know if I should store the generated forms and values generated by the JS and try to validade on the server side or by other hand use another approach like validate all on the client side(easier I think).
My question 1 is: It is possible to do all validations using JS? There is some JS validation framework that will help me on this task? I've goggled and have found LiveValidation(www.livevalidation.com), is this what I need?
Question 2: What problems I will have using this kind of approach(validata all on the client side)?
Some clues, thoughts?
Best Regards,
André, we do that all the time. Javascript validation is a key point and has to be performed before a submit occurs, the main reason being
to make the site / page user friendly
not to actually check, verify, fix the data before it is sent to the server, since the JS validation can be easily bypassed (so there should always be another round of checking server side), thanks to Firebug, Chrome... and a bunch of command line tools.
You use JS validation to, for instance
ensure the user filled all mandatory fields, and point to the missing field (focus)
check the type of the data entered, and warn user
ensure fields consistency (card number, birthdate, fieldX with fieldY...)
...
Besides, to answer your last question, and to paraphrase the beginning of the answer (doesn't hurt)
JS validation does not ensure the data sent to the server is clean / solid / consistent (it cannot as JS validation can easily be bypassed)
the server has to perform the same validation - or stronger - on all fields, and never trust the user input (SQL injection risks etc...).
Yes it is very much possible to do all validations on Client side except for the darkside that all client validations can be bypassed. A good and easy plugin to performa validations is Jquery Validate Plugin
Validations on the client-side is merely just for UX purposes (speed, ease, user-friendliness, immediate response etc.) and never for real validation. JS validation is easy to bypass. One can even submit data to the server without using a form, thus skipping the client-side altogether.
For security purposes, the server should do the validation. Your validation logic should adapt to the dynamic nature of your forms.
As far as I know, dynamic forms usually use arrayed forms, like this one in PHP. That way, it's easy to look into dynamic forms on the server-side, especially those that have repeating groups of fields.
I have a field called price, now how to validate this field by java script? It will take only integer value and dot. It may take decimal point or not.
e.g 200,200.00 both are valid.
How shall I do that?
There are many ways to achieve this.
Without the use of any 3rd party libraries i would recommend using regular expressions.
A possible pattern used to validate price would be
\d[\d\,\.]+
here is a tutorial on using regular expressions to validate fields in java-script
Tutorial
Hope this helps
I want to validate a decimal value in an ASP.NET web page using JavaScript, so that the user can enter numbers with only two decimals. The validation should also consider the current UI culture (e.g. ',' instead of '.'). I use Microsoft's Ajax Framework, is there any function included in the library for such a thing?
If values are separated by spacing you can simply use ^\s*(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)\s*$ regexp (and than use $1 and $2 matches as actual values)
And, more important thing is that all client-side data is insecure by default (because can be forged) so you anyway have to validate it on server.
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.
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