窗体节点
与验证(同步和同步),后处理,以及支持手提栏模板的节点.js的窗体类.
安装
通过 npm数字 :
npm install @bleskomat/form
使用量
用于 快手栏数字 :
const bodyParser = require('body-parser');
const express = require('express');
const Form = require('@bleskomat/form');
const Handlebars = require('express-handlebars');
const path = require('path');
const { ValidationError } = Form;
const app = express();
const hbs = Handlebars.create({
extname: '.html',
helpers: Form.handlebars.helpers,
partialsDir: [
path.join(__dirname, 'views', 'partials'),
Form.handlebars.partialsDir,
],
});
app.engine('.html', hbs.engine);
app.set('view engine', '.html');
app.set('views', path.join(__dirname, 'views'));
app.enable('view cache');
// Parse application/x-www-form-urlencoded:
app.use(bodyParser.urlencoded({ extended: false }));
const form = new Form({
title: 'Form partial example',
action: '/form',
groups: [
{
name: 'login',
inputs: [
{
name: 'username',
label: 'Username',
required: true,
validate: function(value, data) {
// `value` contains the value submitted for this field.
// `data` is an object which contains all form data.
// Perform custom validations for this field here.
// Throw an error here to fail the validation.
// Optionally return an instance of Promise to perform asynchronous validation.
},
process: function(value) {
// `value` contains the value submitted for this field.
// Perform custom processing for this field's value.
return value;
},
},
{
name: 'password',
label: 'Password',
required: true,
},
],
},
],
});
app.get('/form', function(req, res, next) {
res.render('form', {
form: form.serialize(),
});
});
app.post('/form', function(req, res, next) {
// `req.body` is provided by the `bodyParser` middleware.
form.validate(req.body).then(values => {
// Validation successful.
// `values` is an object which contains processed form data.
}).catch(error => {
if (error instanceof ValidationError) {
res.status(400);
} else {
error = new Error('An unexpected error has occurred');
res.status(500);
}
res.render('form', {
form: form.serialize({
errors: [ error.message ],
}),
});
});
});
测试
运行自动测试如下:
npm test
更改日志
见 变动情况
许可证
这个软件是 麻省理工学院执照数字 :
一个简短的,允许性的软件许可证. 基本上,只要在软件/源代码的任何副本中包含原始版权和许可证通知,就可以做任何你想做的事. 这种许可证的使用有许多不同之处.