Best JavaScript solution for checking and interacting with the client side?

Our web forms are really complex. What a great solution for checking form extensibility, preferably one that works with jQuery?

Background:

There is a bit of Ajax on our site, but the real trick is the user experience through 20 multi-page forms or โ€œwizardsโ€. These forms are complex.

  • Presentation: Some fields are float or int. Validation means the separation of non-decimal characters, but we also want to make sure that if the user enters 5 in the price field, the field is updated to 5.00 .
  • Side effects: Some fields have side effects when updating. For example, updating the price or quantity of an item, you need to update the subtotal field.
  • Widget-driven controls: Some fields are hidden and have values โ€‹โ€‹filled with widgets. For example, a map widget allows you to specify a location, and a hidden field is updated using latitude and longitude coordinates, but the location must be within a certain area.
  • Groups: Some fields are groups, such as address / city / state / zip code, and should only be checked after completing all fields.
  • Server side validation:. Validating some fields requires authentication using Ajax requests.
  • Multiple forms per page: Sometimes a user needs to fill out one form before opening a dialog box with another form. The structure should be more universal than binding to onSubmit - we sometimes send several forms in order from one page using Ajax. (For example, we allow users to register and create a widget in one fell swoop, but due to outdated systems, this thread requires two POST requests.)
  • Custom error display: Sometimes errors appear above the fields, sometimes the style of the field changes, and our new projects require tooltips (ala qTip ) for some errors.
  • Happiness: User experience is key, and tactile feedback is important. Any decision
  • Submit buttons . Click the submit button to check everything and then show the answer, but since some checks are performed asynchronously.

We currently use the jQuery Validation library, but our forms seem to outgrow its capabilities. I looked at things like <angular /> , Knockout, and Backbone.js , but I'm worried that they are too heavy or that they will require us to rewrite our interface.

(This should be a wiki community.)

+51
javascript jquery html validation forms
Jan 20 '11 at 19:44
source share
8 answers

This is a shameless plugin, but can I suggest a framework that I developed? I built it based on annotations (a la Hibernate Validator). It supports user restrictions, and I feel that it is quite powerful. Here is also a Stackoverflow question, where I asked for an overview of the structure.

  • Presentation Using special validation constraints, you can bind validation to the onChange element. In addition, since Regula supports custom validators, you can configure your own validator for the field value (so change 5 to 5.00 ).
  • Side Effects : Regula supports side effects with custom limiters.
  • Groups : Regula supports validation groups. You can set up target groups for verification. By combining a custom validator and a group, you can control the behavior of the validator so that it only checks when all the elements of this group are full (you will have to perform this verification through regular Javascript).
  • Server side validation . With user restrictions, you can make an AJAX call for server-side validation. Since the structure is currently structured, this must necessarily be a blocking ajax call. I plan to add an asynchronous function in the future.
  • Multiple forms per page : Regula is not limited to checking one form per page. It can handle multiple forms (not sure if I understood your requirement correctly - so I might not answer this part correctly).
  • Custom error display: Regula does nothing with the page's user interface with respect to validation. When you check, you get a set of constraint violations containing error messages, etc. It is up to you how to display them.
  • Snappiness: I have not performed any tests, so I can not comment on the performance of my infrastructure in this regard.
  • Send buttons: This is what I have yet to solve (asynchronous or synchronous).

Here are some examples:

The following is a standard check with built-in restrictions:

 <input id = "myInput" name = "myInput" type = "text" class = "regula-validation" data-constraints = '@NotEmpty @IsNumeric @Between(min=1, max=5)' /> jQuery(document).ready(function() { // must call regula.binnd() first. The best place would be in an // onload handler. This function looks for elements with // a class name of "regula-validation" and binds the // appropriate constraints to the elements regula.bind(); jQuery("#myForm").submit(function() { // this function performs the actual validation var validationResults = regula.validate(); for(var index in validationResults) { var validationResult = validationResults[index]; alert(validationResult.message); } }); }); 

As you can see, you only work with violation of restrictions, and therefore the method of displaying the error message is completely up to you.

Here is an example of a user constraint:

 regula.custom({ name: "MustBe42", defaultMessage: "The answer must be equal to 42", validator: function() { return this.value == 42; } }); 

And its use:

 <input id = "theAnswerToLifeTheUniverseAndEverything" name = "theAnswerToLifeTheUniverseAndEverything" value = "" class = "regula-validation" data-constraints = "@MustBe42" /> 

Since the validator is a Javascript function, you can force it to do something (so that concerns your question about side effects).

Here is an example of another constraint that takes parameters:

 regula.custom({ name: "DivisibleBy", defaultMessage: "{label} must be divisible by {divisor}", params: ["divisor"], validator: function(params) { var divisor = params["divisor"]; return (this.value % divisor) == 0; } }); 

And use:

 <input id = "number" name = "number" value = "" class = "regula-validation" data-constraints = "@DivisibleBy(divisor=3, label='The Number')" /> 

Here is an example of using validation groups:

 <input id = "score" name = "score" type = "text" class = "regula-validation" data-constraints = '@IsNumeric(label="Score", message="{label} needs to be a number!" groups=[FirstGroup, SecondGroup, ThirdGroup]' /> <input id = "age" name = "age" type = "text" class = "regula-validation" data-constraints = '@IsNumeric(label="Age", message="{label} needs to be a number!" groups=[SecondGroup]' /> <input id = "name" name = "name" type = "text" class = "regula-validation" data-constraints = '@NotEmpty(label="Name", message="{label} cannot be empty!" groups=[FirstGroup]' /> 

And a fragment that only FirstGroup checks (so only score and name are checked):

 var constraintViolations = regula.validate({groups: [regula.Group.FirstGroup]}); var messages = ""; for(var index in constraintViolations) { var constraintViolation = constraintViolations[index]; messages += constraintViolation.message + "\n"; } if(messages != "") { alert(messages); } 

If you plan to try this, I recommend downloading version 1.1.1 . Current documentation is consistent with this version. In 1.2.1, I added support for complex constraints, but I did not update my documentation to reflect this.

I understand if this does not apply to all your problems, or if this is not what you are looking for. I thought I was just putting out. Also, if you do, I will definitely update the documentation to reflect version 1.2.1 . I was busy with school and work, so I did not have time for this.

UPDATE # 1

Sohnee mentioned client-side validation. I'm actually working on integration between Regula and Spring 3. I hope I can release it sometime soon (again, at work and at school). Integration works by translating Hibernate validation restrictions to validation restrictions. Thus, you only need to write the verification code once (basically). However, for user restrictions, you still have to write code on the Javascript side (custom validator). But as soon as you comment on the server side code with the limitations of the Hibernate check, you do not need to do anything on the client side; these restrictions are automatically applied to the formation of elements on the client side.

Matthew Abbott was also able to integrate Regula with ASP.NET MVC .

UPDATE # 2

I have a demo webapp (mavenized) on github that demonstrates the integration between Regula and Spring 3.0.x Web MVC using the Hibernate Validator. It really is not documented or anything else, it is more proof of concept. I plan to add some documentation to the github page about integration and how it works.

UPDATE # 3

I updated the documentation on the wiki and now it corresponds to the latest version 1.2.2 (I made a small correction, so it is 1.2.2 ).

+52
Jan 20 2018-11-21T00:
source share

I have used this jQuery formValidator several times in combination with a number of different environments. I hope this helps, as I rarely spent more than an hour setting it up.

Hurrah!

+13
Jan 24 '11 at 7:19
source share

I would say that the jQuery Validation plugin works fine. I combined it with the metadata plugin to pass server-side validation options to the client. I also included some key points in all forms so that I could use a common template for validation and a few exceptional / user states. This includes a custom warning message and display.

It does not do everything you want out of the box, but it is the best option and the best default behavior that I have seen. Again, I use metadata (the data-meta attribute) with it. And it can be bent at your will. I also use metadata to bind controls to client-side input elements. This shares my client-side logic with the server side, but easier in the long run, trying to insert js from the server-side logic.

+8
Jan 30 2018-11-11T00:
source share

Parsley.js looks like a good and popular choice at the time of writing (August 2013).

+5
Aug 19 '13 at 9:55 a.m.
source share

Answering this myself, as someone from our team noticed Validator from jQuery Tools !

  • Presentation Supports HTML5 input fields. pattern make sure that the user can only enter the test in a specific pattern.
  • Side effects . Event onFail in the form and in separate fields: onFail and onSuccess
  • Widget driven elements - encouraged by "custom input types". The main demo includes only the natural number "age".
  • Groups . Write a "functional mate" whose sole purpose is to filter the fields that need to be checked.
  • Server - side validation โ€” doing this and doing it sensibly โ€” depends on your validator calling the callback (therefore it is not asynchronous) instead of the return value.
  • Multiple forms per page - jQuery Tools looks very good and this should not be a problem.
  • Customizable error indication . Errors near the fields? All in one place? No problems. Still not good enough? Bind events to failure. Even uses default tooltips.
  • Snappiness - Demos are very fast.
  • Send buttons - no problem.

Update: Yes, I just reworked a piece of our site using the tooltips of jQuery Tools. Fantastic!

+2
Mar 04 '11 at 23:29
source share

Server-side validation scanning.

Deliver the results of such validation using an AJAX request if you want ... or use a server structure that will also add client-side validation, but do not write it down twice.

+1
Jan 28 2018-11-11T00:
source share

Go with jQuery validation plugins. This has never let me down so far.

0
May 20 '14 at 12:16
source share
  function isEmpty(text) { if(text == undefined) { return true; } if(text.replace(/\s+/g, ' ').length == 0) { return true; } return false; } function isValidBoolean(text) { if(text == undefined || (text.toLowerCase() != "true" && text.toLowerCase() != "false")) { return false; } return true; } function isValidDouble(text) { var out = parseFloat(text); if(isNaN(out)) { return false; } return true; } function isValidLong(text) { var out = parseInt(text); if(isNaN(out)) { return false; } return true; } function isValidDate(text) { if(Date.parseString(text, 'MM/dd/yyyy HH:mm:ss') == null) { return false; } return true; } function hasDuplicates(array) { var valuesSoFar = {}; for (var i = 0; i < array.length; ++i) { var value = array[i]; if (Object.prototype.hasOwnProperty.call(valuesSoFar, value)) { return true; } valuesSoFar[value] = true; } return false; } 
0
Mar 31 '15 at 12:55
source share



All Articles