Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9146

Express Validatorを使ってみる(API変更後)

$
0
0

はじめに

完全自粛中なのでNode.js超入門第2版でnode.jsの勉強をしていました。
express-validatorがAPI変更に伴って、参考書通りのソースコードだとバリデーションが実行されなかったので、変更点も交えながら記事投稿します。

環境

・node 12.7.0
・express 4.16.1
・express-validator 5.3.1

Node.js超入門第2版 P334~335

app.js
varvalidator=require('express-validator');app.use(validator());
hello.js
router.get('/add',(req,res,next)=>{vardata={title:'Hello/Add',content:'新しいレコードを入力:',form:{name:'',mail:'',age:0}}res.render('hello/add',data);});router.post('/add',(req,res,next)=>{req.check('name','名前は必ずご入力してください。').notEmpty();req.check('mail','メールアドレスをご入力してください。').isEmail();req.check('age','年齢は整数をご入力してください。').isInt();req.getValidationResult().then((result)=>{if(!result.isEmpty()){varre='<ul class="error">';varresult_arr=result.array();for(varninresult_arr){re+='<li>'+result_arr[n].msg+'</li>';}re+='</ul>';vardata={title:'Hello/add',content:re,form:req.body}res.render('hello/add',data);}else{varnm=req.body.name;varml=req.body.mail;varag=req.body.age;vardata={'name':nm,'mail':ml,'age':ag};varconnection=mysql.createConnection(mysql_setting);connection.connect();connection.query('insert into mydata set ?',data,function(error,results,fields){res.redirect('/hello');});connection.end();}});});

API変更後

hello.js
// Express-validatorを読み込むconst{check,validationResult}=require('express-validator/check');router.get('/add',(req,res,next)=>{vardata={title:'Hello/Add',content:'新しいレコードを入力:',form:{name:'',mail:'',age:0}}res.render('hello/add',data);});router.post('/add',[check('name','名前は必ずご入力してください。').not().isEmpty(),check('mail','メールアドレスをご入力してください。').isEmail(),check('age','年齢は整数をご入力してください。').isInt()],(req,res,next)=>{// getValidationResult()ではなく、validationResult(req)でバリデーションの実行結果を受け取る。varresult=validationResult(req);// チェック項目があった場合if(!result.isEmpty()){varre='<ul class="error">';varresult_arr=result.array();for(varninresult_arr){re+='<li>'+result_arr[n].msg+'</li>';}re+='</ul>';vardata={title:'Hello/add',content:re,form:req.body}res.render('hello/add',data);}// チェックを通過した場合else{varnm=req.body.name;varml=req.body.mail;varag=req.body.age;vardata={'name':nm,'mail':ml,'age':ag};varconnection=mysql.createConnection(mysql_setting);connection.connect();connection.query('insert into datamy set ?',data,function(error,results,fields){res.redirect('/hello');});connection.end();}});

モジュールのロードの仕方とValidatorの追加の仕方

app.use(validator());が使えなくなっているため。

req.check()ではなくcheck()でExpressValidator.Validatorのオブジェクトを返す

app.post('/add',[],(req,res,next)=>{});

第1引数にPOST処理後のルーティング処理、第2引数にチェック項目を配列で、第3引数にコールバック関数を入れる

参考

https://express-validator.github.io/docs/index.html
https://www.shuwasystem.co.jp/book/9784798055220.html

おわりに

参考書で勉強していて困っていた人の助けになれれば光栄です。


Viewing all articles
Browse latest Browse all 9146

Trending Articles