やりたいこと
HTMLの <form>
要素で、任意の <input>
要素の入力値をサーバに送信したくない。たとえば UI 制御用のダミーの入力欄があるときとか。
解決策
JS使えば色々できるけど、素のHTMLでもできる。
-
disabled
属性を 指定する- disabled な input はユーザにより変更不可能かつ、無効なコントロールとみなされてsubmit時に値が送信されなくなる。
-
name
属性を空にする- name 属性が空の input は、無効なコントロールとみなされる。
- 裏技っぽいけど、W3Cで定められた挙動。
name
は(厳密にはそうではありませんが)必須の属性と考えてください。入力欄にname
が指定されていなかった場合やname
が空欄だった場合、その入力欄の値はフォームと一緒に送信されません。(無効なコントロール、チェックされていないラジオボタン、チェックされていないチェックボックス、リセットボタンも送信されません。)
from https://developer.mozilla.org/ja/docs/Web/HTML/Element/input#name
A successful control must be defined within a FORM element and must have a control name.
from https://www.w3.org/TR/html4/interact/forms.html#h-17.13.2
実験してみた
適当なフォーム
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample Form</title>
</head>
<body>
<form action="" method="post">
normal input: <input type="text" name="your_name" value="Joao">
nameless input: <input type="text" value="no_name">
disabled input: <input type="text" name="disabled_input" disabled="1" value="disabled">
<input type="submit" value="Submit!">
</form>
</body>
</html>
ChatGPTに適当に作ってもらったテストサーバ。
HTMLを返してリクエスト内容をログします
const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
const server = http.createServer((request, response) => {
// リクエスト内容を出力
console.log(`Received request: ${request.method} ${request.url}`);
let postData = '';
request.on('data', function(chunk) {
postData += chunk;
}).on('end', function() {
console.log(` body: ${postData}`);
})
// リクエストに対応するファイルのパスを取得
const parsedUrl = url.parse(request.url);
let pathname = `.${parsedUrl.pathname}`;
const filePath = path.join(__dirname, pathname);
fs.exists(filePath, function(exists){
if(!exists){
response.statusCode = 404;
response.end(`File ${pathname} not found!`);
return;
}
// ファイルが存在する場合、その内容を返す
fs.readFile(filePath, function(err, data){
if(err){
response.statusCode = 500;
response.end(`Error getting the file: ${err}.`);
} else {
response.setHeader('Content-type', 'text/html');
response.end(data);
}
});
});
});
const port = 8080;
// HTTPサーバの起動
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}/`);
});
以下で起動
$ node index.js
ブラウザで http://localhost:8080/form.html を開いて、 submit したら以下のようなログがでた。
disabled=true
のものと name
が空のものは送信されていないのが確認できた。へー。
Received request: POST /form.html
body: your_name=Joao