12
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JS】 テキストエリア内での改行を禁止にする

12
Last updated at Posted at 2026-06-24

やりたいこと

  • textareaに入力する文字(コピペも含む)を改行出来ないようにしたい

経緯

  • formのテキストボックス <input type="text"><textarea> に変更することになった。
  • ただ、「入力するテキストは単一行で」という仕様はそのままにする必要があったので、textareaに入力するテキストを改行出来ないように修正する必要がある。

バージョン

vue@3.2.47
typescript@4.9.5
vee-validate@4.15.1

コード

vue.jsのフォーム内に設置しているtextareaのため、書き方は以下の通り。
フォーム入力では基本的にv-modelを使用するが、今回はリアルタイムで入力したテキストを元にイベントを実行するため @input を使用した。

<textarea
    placeholder="テキストをここに入力"
    :value="formText"
    @input="handleInputText"
    @keydown.enter.prevent
></textarea>

エンター時の動作を無効にする

テキスト入力時にエンターを押した時、改行させないようにする

@keydown.enter.prevent

入力時にイベント handleInputText() を実行

改行を含むテキストをコピー&ペーストした際にも動的に改行が取り除かれる

@input="handleInputText"
<script setup lang="ts">

const formText = ref<string>("");

const handleInputText = (e: Event) => {
    const target = e.target as HTMLTextAreaElement
    // 入力した値から改行文字を取り除く
    const sanitizedValue = target.value.replace(/[\r\n]+/g, '')

    // フォームの入力情報を更新
    formText.value = sanitizedValue

    // 画面のテキストエリア上での表示も更新
    target.value = sanitizedValue
}
</script>

vee-validateのFieldを使用している場合

vee-validate の Field を使用し、Field側でv-modelを指定している場合の書き方

  • v-slot: オブジェクトを入力要素/入力にバインド
<Field
  name="form_text"
  label="テキスト"
  v-slot="{ field }"
  v-model="formText"
>
  <textarea
    v-bind="field"
    @input="handleInputText($event, field.onInput)"
    @keydown.enter.prevent
  ></textarea>
</Field>
<ErrorMessage name="form_text">

入力操作を受け取ってイベント handleInputText() を実行

@input="handleInputText($event, field.onInput)"
<script setup lang="ts">

const formText = ref<string>("");

const handleInputText = (event: Event, onInput: (e: Event) => void) => {
    const target = e.target as HTMLTextAreaElement
    // 入力した値から改行文字を取り除く
    const sanitizedValue = target.value.replace(/[\r\n]+/g, '')

    // フォームの入力情報を更新
    onInput(event);

    // 画面のテキストエリア上での表示も更新
    target.value = sanitizedValue
};
</script>

Fieldを使用した場合の入力値の受け渡しが少しややこしく感じましたが、これでテキストの改行を禁止させることができました!

参考
https://vee-validate.logaretm.com/v4/api/field

12
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?