0
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 1 year has passed since last update.

はじめに

備忘録として記事にします。
より良い実装方法があれば指摘していただけると幸いです。

全角文字の入力を弾く目的として、任意のユーザーIDを作成してもらうときに半角のみ受け付けるといったことが挙げられます。

下記コードを編集することで、Webアプリ側で、使用できない文字(使用してほしくない文字)を打ち込めないようにすることも可能になります。

コード

validationCheck.ts
export const varidationCheck = (checkText: string) => {
  const regex = new RegExp(/^[0-9a-zA-Z]*$/);

  return regex.test(checkText)
}
page.tsx
'use client';
import { useState } from 'react';
import { validationCheck } from './validationCheck';


const Page = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  const handleChange=()=>{
    if(!inputRef.current) return;
    if(!validationCheck(inputRef.current.value)){
      inputRef.current.value = inputRef.current.value.slice(0, -1);
    }
  }

  return (
    <div>
     <input ref={inputRef} onChange={handleChange}/>
    </div>
  );
};

export default Page;

説明

validationCheck.tsで使用できる文字の正規表現を作成しておき、渡された文字列が正規表現を守れているか(正しい表現ではないかもしれません。)確認しています。
返り値はbooleanです。

page.tsxのhandleCheck関数でvalidationCheckを呼び出し、input要素に変更があるたびに全角文字の入力がないか確認します。
全角文字の入力があった場合、validationCheckからfalseが返ってきます。
その時には、inputRef.current.valueに最後の文字を除いた文字列を代入することで全角文字の入力を弾くことを行っています。

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