22

I am looking for a javascript lib which enables me to store (html) forms in JSON format, with a bit of intelligence built into validate inputs client side. Something like:

function FormController(){
  this.user = {
    name: 'John Smith',
    address:{line1: '123 Main St.', city:'Anytown', state:'AA', zip:'12345'},
    contacts:[{type:'phone', value:'1(234) 555-1212'}]
  };
  this.state = /^\w\w$/;
  this.zip = /^\d\d\d\d\d$/;
}

(This is taken from http://docs.angularjs.org/#!cookbook.form ). It's almost what I want, as it offers basic client side validation with regular expressions and you can provide defaults but it appears to still need you to create the HTML form.

I want something that only requires the definition. Any ideas?

Ed_
  • 1,676
  • 2
  • 13
  • 22
  • 3
    Little bit outdated but since you are mentioning **AngularJS** as a link you could also try out automatic form generation from JSON schemas via [Angular Schema Form](https://github.com/Textalk/angular-schema-form) it also comes with support for Bootstrap 3 :D – Jeremy S. Aug 20 '14 at 15:18

10 Answers10

18

In shameless self promotion I would also like to mention my jQuery.dForm plugin. It's been around for a while now and support the jQuery validation plugin, jQuery UI and is easily extensible. This is how it looks:

var formdata =
{
    "action" : "index.html",
    "method" : "get",
    "elements" : 
    [
        {
            "name" : "textfield",
            "caption" : "Label for textfield",
            "type" : "text",
            "value" : "Hello world"
        },
        {
            "type" : "submit",
            "value" : "Submit"
        }
    ]           
};
$("#myform").buildForm(formdata);

// Or to load the form definition via AJAX
$("#myform").buildForm("http://example.com/myform.json");
Daff
  • 43,734
  • 9
  • 106
  • 120
  • @Daff - this is great for quickly and easily generating the form HTML. However, I want to handle form-submit myself, and *not actually submit* through the `
    ` attribute. How can the default form-submit event be blocked or otherwise intercepted? At the moment, my work-around is to add my own `
    – Gene Bo Sep 26 '18 at 18:17
10

I would suggest using JSON Form.

It takes a JSON Schema and can instantly make a form for it, and additionally give you options to customize the form further. E.g.:

$('#myform').jsonForm({
  schema: {
    name: {
      type: 'string',
      title: 'Name',
      required: true
    },
    age: {
      type: 'number',
      title: 'Age'
    }
  }
});

…would generate a form with two inputs in #myform element. (jQuery is optional.)

Using the standardized format JSON Schema gives other great advantages and more tools to work with the data definition.

fiddur
  • 1,768
  • 15
  • 11
  • 1
    It has a really great set of examples at https://github.com/joshfire/jsonform/tree/master/playground and can be used to create forms with arrays of nested objects. – yegeniy Mar 02 '14 at 22:32
5

I would agree with Jeremy S Angular Schema Form is outstanding. It follows the same pattern as JSON Form and I have started using it in production and it is working very well.

It is also extensible and I quite quickly wrote a tool to read hyper-schema definition and pull in select field options from an external source and watch other related fields for their data before doing so. It took only a day to build that, suffice to say it is really easy to extend and as it also takes advantage of Angular I would class it as the best choice.

If you are not using Angular then JSON Form would be my preferred option since I see its schema and form pattern emerging as a bit of a standard with these two projects using it. Also given my experience working in enterprise service management it makes sense as nearly all tools for service management have a data model and then a form design administration component for extending the model.

Disclaimer: I was not maintaining Angular Schema Form when I wrote this.

I only became the maintainer on the project a year later because I already loved it.

Anthropic
  • 681
  • 1
  • 11
  • 29
4

Definitely check out Alpaca: http://www.alpacajs.org

It renders HTML forms from JSON Schema using Bootstrap, jQueryUI, jQuery Mobile or straight web controls. It has a large library of controls and all sorts of nifty features.

We use it at Cloud CMS (http://www.cloudcms.com) to render some really intuitive UIs.

Alpaca itself is Apache 2.0 licensed and on GitHub (https://github.com/gitana/alpaca).

The coming 1.5.0 release introduces pure Handlebars support and custom gulp builds. Pretty cool stuff.

3

May I humbly suggest Metawidget?

It generates HTML forms from arbitrary complex JSON objects. Simple JavaScript example:

<!DOCTYPE HTML>
<html>
   <head>
      <script src="http://metawidget.org/js/4.0/metawidget-core.min.js"></script>
      <style>
         #metawidget {
            border: 1px solid #cccccc;
            width: 250px;
            border-radius: 10px;
            padding: 10px;
            margin: 50px auto;
         }
      </style>
   </head>
   <body>
      <div id="metawidget"></div>
      <script type="text/javascript">
         var mw = new metawidget.Metawidget( document.getElementById( 'metawidget' ));
         mw.toInspect = {
            firstname: 'Homer',
            surname: 'Simpson',
            age: 36
         };
         mw.buildWidgets();
      </script>
   </body>
</html>

It also supports:

  • augmenting the JSON object with additional sources of metadata, such as JSON Schema or metadata from REST services
  • frameworks such as JQuery UI, JQuery Mobile, AngularJS
  • third-party component libraries and validators
  • pluggable layouts
Richard Kennard
  • 1,325
  • 11
  • 20
  • 1
    You should probably more explicitly mention your involvement in the framework as it's creator, it is a cool framework, congrats. Glad you have json-schema support, I'm hoping to progress a json-ui-schema proposal at json-schema-org to make UI generation more consistent across json-schema based UI implementations :) – Anthropic Aug 10 '17 at 00:25
3

Angular doesn't solve your problem out of the box because it asumes that you have static html which you want to bind some data to.

Having said that you can use angular to fulfill your objectives. You can create a new tag (angular widget) which will take a js object and dynamically creates the form DOM along with all the angular validation attributes. You then compile the form with angular's compiler and attach it to your page. This will result in dynamically created form with all the existing angular's validation and databinding features working just like with a static html.

There is nothing I can think of that would prevent you from doing this via angular.widget api, but it's not a trivial task.

Can you tell me more about your data structures? I wonder if having just a set of forms and using the right one at the right time wouldn't be sufficient. Why do you need the form creation to by completely dynamic and data-driven?

UPDATE: The angular solution can be found at https://groups.google.com/forum/#!topic/angular/f8KbLtT_Mqs

Igor Minar
  • 9,574
  • 3
  • 22
  • 13
  • I am working on making a plugin system to enable 3rd parties to add components. I want them to be able to request user data but I dont want to give them access to the actual js or html of my page. Thus they need a flexible option to define the user input they require and should get an option for both client side data validation and server side validation. – Ed_ Apr 01 '11 at 22:07
  • 1
    sweet. that sounds really good. can we move this discussion to our mailing list: https://groups.google.com/forum/?lnk=srg#!forum/angular the stack overflow text area is killing me. Just start a new thread there. We'll repost the final resolution on stack overflow afterwards. – Igor Minar Apr 01 '11 at 22:29
1

I've used Jeremy Dorn's JSON Editor for various applications and have always been satisfied with it! It uses JSON Schema, and adds some options for the form generation (as you could conceivably have a variety of inputs for a given type of data structure)

https://github.com/jdorn/json-editor

Fabio Beltramini
  • 2,441
  • 1
  • 16
  • 25
1

Check out jQuery Templates plugin.
A little while back I wrote up a little blog post on Client-side Data Binding with jQuery Templates. It seems to me that this is exactly what you're looking for.

Kon
  • 27,113
  • 11
  • 60
  • 86
  • Interesting, this isn't quite what I am looking for though. Problem is that you have to define the html upfront, I don't know in advance the fields I want, thus I want each field to be created from the json object. – Ed_ Apr 01 '11 at 04:42
  • Then I'm afraid you'll have to write your own generic routine for creating elements/tables and rows. – Kon Apr 01 '11 at 15:23
0

Check out InputEx, it seems exactly what you want.

It uses JSON to define the entire form:

// Create a schemaIdentifierMap 
var schemaIdentifierMap = {
 // Person definition
 "Person": {
    "id": "Person",
    "description":"A person",
    "type":"object",
    "properties": {
        "name": { "type":"string"},
        "born" : { "type":"string", "format":"date", "optional":true},
        "gender" : { "type":"string", "choices": [ {"value":"male","label":"Guy"}, {"value":"female","label":"Girl"} ]},
        "grownup": { "type": "boolean" },
        "favoritecolors": { "type": "array" },
        "address": { 
            "type":"object",
            "properties":{
                "street":{"type":"string"},
                "city":{"type":"string"},
                "state":{"type":"string"}
            }
        }
    }
 }
};

(from http://neyric.github.com/inputex/examples/json-schema.html)

dakhota
  • 39
  • 3
0

Take a look at brutusin:json-forms.

It accepts a JSON-Schema and the initial JSON data to populate the form.

idelvall
  • 1,536
  • 15
  • 25