js regular check for special invisible characters

background

In the input box of the form, the user may directly copy and paste from Excel or other places. At this time, submitting to the backend will cause the obtained user input to contain some special invisible characters, such as tab keys or tab characters. The front end does some checks on user input to check whether there are invisible characters.

method

The 0~31st characters (the first 32 characters) and the 127th
character (the last character) in the ASCII code are invisible (cannot be displayed), but they all have some special functions, so they are called control characters ( Control
Character) or Function Code (Function Code).

The information of the key part of the ASCII code is as follows:

insert image description here
insert image description here
insert image description here

Note that the characters 0~31 and 127 here are control characters (invisible characters). We can check whether they contain the hexadecimal characters in the regular pattern to determine whether they contain special characters.

For the detailed meaning of these control characters, please refer to: Interpretation of ASCII control characters

Complete ASCII code table:
insert image description here

check

Online regular checking tool: rookie tool - regular expression online test

A simple string of test text:

ABC1823中文0456def$%#?.			mMo

1. Check whether there are special invisible characters,
as long as there is an invisible character, an error will be reported

[\x00-\x1F\x7F]

Note that there are two 0s here. \x0-\x1F\x7FIt is wrong to use this format, and normal verification cannot be performed.

insert image description here

2. Check for invisible characters

[^\x00-\x1F\x7F]+

Note that ^the position of here should not be written outside, the outside indicates what starts with

insert image description here

the code

import React,{
    
    useState} from "react";
import {
    
    Input,message} from "antd";

const RegTestInput = function(){
    
    
	
	const testValue = (e) => {
    
    
		const {
    
     value } = e.target;
		if(value) {
    
    
			const reg = /[\x00-\x1f\x7f]/
			if(reg.test(value)){
    
    
				message.error("不允许包含特殊字符")
			}
		}
	}
	
	return (
		<div>
			<Input onChange={
    
    testValue} />
		</div>
	)
}

Guess you like

Origin blog.csdn.net/Charonmomo/article/details/130862041