1
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?

More than 3 years have passed since last update.

JavaScriptでinputの入力欄にスペース、空白を入力させないようにする方法

Last updated at Posted at 2021-06-30

JavaScriptでinputの入力欄にスペース、空白を入力させないようにするに方法なります。
フォームなどの入力欄作成時に使えるかと思います。

JavaScriptのreplace()メソッドを使う

<input id="input" type="text" value="" />

<script>
  const input = document.getElementById('input')
  input.addEventListener('input', () => {
    const inputCheck = /\s+/g // 空白の正規表現
    const value = input.value
    input.value = value.replace(inputCheck, '')
  })
</script>

JavaScriptのreplace()を使い、空白やスペースを除いてinputのvalueにセットし直してます。
空白があるかを判別したい時は、test()が使えます。

const inputCheck = /\s+/g;
const value = "abcdefg";
if (inputCheck.test(value)) {
  console.log('空白があります')
}

Vue.js(Nuxt.js)の場合

<template>
  <div>
    <input v-model="inputForm" type="text" />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  data() {
    return {
      inputForm: ''
    }
  },
  watch: {
    inputForm(inputForm) {
      const inputCheck = /\s+/g // 空白の正規表現
      this.inputForm = inputForm.replace(inputCheck, '')
    }
  }
})
</script>

Vue.js(Nuxt.js)の場合は、watchで入力を監視することで実装できます。

参考

1
0
2

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
1
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?