You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中表单验证失败时如何保留数据?(Express Validator+Handlebars)

Fix for Retaining Form Input Values After Express Validator Validation with Handlebars

Got it, I see exactly what's going on here. Your validation works and errors show up correctly, but the form isn't remembering what the user typed before submission—let's fix that step by step.

The Root Issue

Your Handlebars template isn't actually using the title and description values you're passing from the controller. Right now, your input and textarea elements have no logic to populate their content with submitted values. Also, when users first load the page via the GET request, you aren't initializing those variables, which can cause Handlebars to throw silent errors.


Step 1: Update the Handlebars Template

We need to bind the form fields to the variables you're passing, with fallbacks to empty strings (so fields don't show undefined on first load). I'll also fix a couple of typos in your original template (<lebel> → <label>, form- control → form-control):

<div class="container">
 <h1>Create New Post</h1>
 <div class="row p-4">
 <div class="col-md-10">
 <!-- Display error message if present -->
 {{#if error_message}}
 <div class="alert alert-danger">{{error_message}}</div>
 {{/if}}
 <form action="/admin/news-upload" method="post">
 <div class="form-group">
 <label for="title">Title</label>
 <input type="text" class="form-control" name="title" id="title" placeholder="Enter The Title" value="{{title || ''}}">
 </div>
 <div class="form-group">
 <label for="description">Content</label>
 <textarea name="description" id="description" class="form-control" placeholder="Enter your content here" rows="10">{{description || ''}}</textarea>
 </div>
 <button class="btn btn-outline-success btn-lg" type="submit">Create Post</button>
 </form>
 </div>
 </div>
</div>

Step 2: Initialize Values in the GET Controller

When users first visit /news-upload via a GET request, your getNews method needs to pass empty values for title and description to avoid Handlebars treating them as undefined. Update your controller's getNews function:

getNews: (req, res) => {
 // Initialize empty values so Handlebars has something to render
 res.render('admin/news', {
 title: '',
 description: ''
 });
}

Step 3: Double-Check Your POST Controller Setup

Your existing submitNews logic is already passing req.body.title and req.body.description correctly—just make sure you've imported validationResult at the top of your controller file:

const { validationResult } = require('express-validator');

Optional: Optimize with connect-flash

Since you're using connect-flash, you can store error messages there instead of passing them directly, which keeps your code cleaner. Here's how:
In your POST controller:

submitNews: (req, res) => {
 const errors = validationResult(req);
 if (!errors.isEmpty()) {
 req.flash('error', errors.errors[0].msg);
 return res.render('admin/news', {
 title: req.body.title,
 description: req.body.description,
 messages: req.flash()
 });
 }
 // Rest of your logic for valid submissions
}

Then update the error section in your template:

{{#if messages.error}}
 <div class="alert alert-danger">{{messages.error.[0]}}</div>
{{/if}}

This is more scalable if you add multiple error types later.

That should do it! Now when validation fails, the user's input will stay in the form fields for a smoother experience.

内容的提问来源于stack exchange,提问作者Drilldoge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:05:40