[英]how to restrict ONLY space and special characters to be entered in the input texbox. We need to allow both when entered with alphabets
預期結果:- 它不應該只接受空格或特殊字符。 但是當使用字母輸入時,它應該接受所有字符和空格。
<div>
<div className={createNewContainerStyles}>
<p>Reason</p>
<TextArea value={reason} placeholder='Add reason' showCount maxLength={250} onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setReason(e.target.value)
}}>
</TextArea>
<div>
<Button type="default"
loading={loading}
onClick={onClose}>Cancel
</Button>
<Button type="primary" disabled={!reason} loading={loading} onClick={onBlacklistRequest}>Add
</Button>
</div>
</div>
</div>
解決方法:檢查字符串是否包含字母。 如果 String 僅包含特殊字符或空格會引發錯誤,並且如果字符串包含字母,則無需檢查空格和特殊字符。
這里:我使用正則表達式來檢查字符串。
import React, { useState } from "react";
export function App() {
const [reason, setReason] = useState("");
const verifyInput = (value) => {
// Check String contain alphanumeric characters or not
if(/[a-zA-Z]/g.test(value)){
setReason(value);
} else {
// Handle Erorr
}
};
return (
<div>
<p>Reason</p>
<textarea
value={reason}
placeholder="Add reason"
maxLength={250}
onChange={(e) => verifyInput(e.target.value)}
/>
</div>
);
}
要添加到@gadgetvala 的答案,您可以使用pattern
屬性(用於input
元素):
<div>
<div className={createNewContainerStyles}>
<p>Reason</p>
<input type="text" value={reason} pattern="^[a-zA-Z][^$]+" placeholder='Add reason' showCount maxLength={250} onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setReason(e.target.value)
}}/>
<div>
<Button type="default" loading={loading} onClick={onClose}>Cancel
</Button>
<Button type="primary" disabled={!reason} loading={loading} onClick={onBlacklistRequest}>Add
</Button>
</div>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.