리액션 js의 텍스트 필드에 길이 제약 조건을 넣습니다.
카드 번호의 유저로부터 입력을 받고 있습니다만, 유저가 입력하는 길이는 12보다 작지 않게 해 주세요.여기 제 텍스트 필드의 선언문이 있습니다.
<TextField
id="SigninTextfield"
label="Aadhaar number"
id="Aadhar"
lineDirection="center"
required={true}
type="number"
maxLength={12}
style={styles.rootstyle}
erorText="Please enter only 12 digits number"
/>
지금은 javascript를 사용할지 이벤트 핸들러를 사용할지 모르겠습니다.
설정할 수 요.maxLength텍스트 상자의 텍스트를 제한하기 위한 속성입니다.
onChange할 수 있는 maxLengthinputProps(소문자 i, Input Props가 아님) 소품material-ui TextField.
<TextField
required
id="required"
label="Required"
defaultValue="Hello World"
inputProps={{ maxLength: 12 }}
/>
으로 모든 네이티브 하려면 을 합니다.inputProps★★★★★★ 。
TextField API 링크
나는 여기서 다른 해결책을 찾았다.
<TextField
required
id="required"
label="Required"
defaultValue="Hello World"
onInput = {(e) =>{
e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,12)
}}/>
<TextField
autoFocus={true}
name="name"
onChange={handleChange}
placeholder="placeholder"
id="filled-basic"
variant="filled"
size="small"
fullWidth
inputProps={{
maxLength: 25,
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
<TextField
id="username"
name="username"
label={translate('username')}
onChange={handleChange}
onBlur={handleBlur}
value={values.username}
error={Boolean(errors.username) && touched.username}
helperText={(errors.username && touched.username && translate(errors.username))}
required
inputProps={{maxLength :20}}
/>
Material-ui는 ?<TextField />에 '''가 .maxlength html, html은 html입니다.<input>이 기능을 사용하기 위해 별도의 기능을 만들 필요가 없습니다. 베이스로 .<input>, " " 를 사용한 아트리뷰트inputProps.
실제 답은 다음과 같습니다.
inputProps={
{maxLength: 22}
}
// Result => <input maxlength="yourvalue" />
은, 「」를 합니다.maxlength가 되는 「」의 <input>다음과 같습니다.<input maxlength="yourvalue" />또은 '아까운 것은 없다'는 말을 한다는 것입니다inputProps andInputProps로 하고 것은 글자입니다.inputProps.
그 사이의 행동에서 이상한 점을 발견했어요TextField ★★★★★★★★★★★★★★★★★」Input
서로 매우 비슷하지만 다음과 같은 문제가 있습니다.
를 대문자인 TextField와 InputProps를 합니다."I"는 'Adorments 가 만 만 만 만 만 만 만 만 만 만 만 만 만 만 만 만 만 만 만 만 , , , , , , , , lowercase lowercase lowercase lowercase , , , , , , , , , 。inputProps ", ",maxLength as Html TAKE 입니다.valid단, 단은 .adorments
나는 결국 그것을 이용하게 되었다.INPUTTextField 이렇게 쓰면 요.adorments
<TextField
variant="outlined"
required
fullWidth
error={errors.email}
id="email"
label={t("signup-page.label-email")}
name="email"
onChange={handleChange}
inputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton aria-label="toggle password visibility">
<EmailIcon />
</IconButton>
</InputAdornment>
),
maxLength: 120,
}}
/>
에서는, 「Code」를 합니다.adorment 「 「」는 할 수 없습니다.maxLength아주머니'로inputProps
인 예시로,, . 보시다시피, 저는 이 코드를 이전 스타일로 받아들였습니다.Form Control", " " "outlinedInput
<FormControl variant="outlined" fullWidth>
<InputLabel htmlFor="firstName">Password</InputLabel>
<OutlinedInput
value={values.firstName}
autoComplete="outlined"
name="firstName"
variant="outlined"
required
fullWidth
error={errors.firstName}
id="firstName"
label={t("signup-page.label-firstname")}
onChange={handleChange}
autoFocus
inputProps={{ maxLength: 32 }}
/>
</FormControl>
해결책마지막으로 권장하는 것은 를 사용하는 것입니다.따라서 다른 방법으로 사용할 수 있습니다.Adorments, 「」도 있습니다.maxLength
다음에 나타내는 작업 예를 나타냅니다.FormControl OutlinedInput,inputProps-maxLength 끝 리리 > 。Adorment ★★★★★
<FormControl variant="outlined" fullWidth>
<InputLabel htmlFor="password">Password</InputLabel>
<OutlinedInput
value={values.passwordConfirm}
variant="outlined"
required
fullWidth
error={errors.passwordConfirm}
name="passwordConfirm"
label={t("signup-page.label-password-confirm")}
type={values.showPasswordConfirm ? "text" : "password"}
id="password-confirm"
onChange={handleChange}
inputProps= {{maxLength:32}}
endAdornment= {
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword("passwordConfirm")}
onMouseDown={handleMouseDownPassword}
>
{values.showPasswordConfirm ? (
<Visibility />
) : (
<VisibilityOff />
)}
</IconButton>
</InputAdornment>
}
/>
{errors.passwordConfirm && (
<p className="error"> {errors.passwordConfirm} </p>
)}
</FormControl>
5를 사용하는 경우5.0.6대한 있기
<TextField
id="standard-textarea"
label="A label"
placeholder="Some text here"
multiline
variant="standard"
defaultValue={"Hello"}
inputProps={{
maxLength: 255,
}}
InputProps={{
disableUnderline: true,
}}
/>
TextField를 inputProps ★★★★★★★★★★★★★★★★★」InputProps그러나 일부 속성은 반대로 작동하지 않습니다.
maxLength does does does does does does 。InputProps , , , , 같은 입니다.disableUnderline MUI 5에서 inputProps.
가능한 한 조심해라typo와 함께i.
자세한 내용은 API(https://mui.com/api/text-field/를 참조하십시오.
Firefox에서는 16자리보다 큰 숫자에 대해 허용되는 답변이 작동하지 않습니다.숫자들은 그저 이상한 방식으로 행동할 뿐이다.
길이가 22인 필드의 경우 다음과 같이 처리했습니다.
<TextField
required
validateOnBlur
field="cbu"
label="22 dígitos del CBU"
validate={validate.required}
type="text"
inputProps={
{maxLength: 22}
}
onInput={(e) => { e.target.value = e.target.value.replace(/[^0-9]/g, '') }}
/>
기본적으로 원어민maxLength텍스트 필드에 대한 제약 조건과 문자열에서 숫자로의 변환이 "온 더 플라이"에 추가됩니다.
개선.
또, 이것을 재사용할 수 있고, 보다 의미 있는 것으로 하는 것을 선호할 수도 있습니다.
# constraints.js
const onlyNumbers = (e) => { e.target.value = e.target.value.replace(/[^0-9]/g, '') };
# form.js
<TextField
field="cbu"
label="22 dígitos del CBU"
inputProps={
{maxLength: 22}
}
onInput={(e) => onlyNumbers(e) }
재료 설계<TextField />컴포넌트에는 없습니다.length소유물.
다음에서 작성하실 수 있습니다.onChange()방법.
updateTextField(event,value){
if(value.length <= 12){
//Update your state
}
else{
//Value length is biggest than 12
}
}
<TextField
id="SigninTextfield"
label="Aadhaar number"
id="Aadhar"
lineDirection="center"
required={true}
type="number"
onChange={(e,v) => this.updateTextField(e,v)}
style={styles.rootstyle}
erorText="Please enter only 12 digits number"
/>
변경 핸들러에, 기입해 주세요.
if (event.target.value.length !== maxLength ) return false;
저도 비슷한 문제가 있었습니다만, Textarea는자동 크기 조정.불행하게도,
inputProps={{ maxLength: 12 }}
텍스트 영역과 함께 작동하지 않음자동 크기 조정.
다음 회피책은 텍스트 영역에 적용됩니다.자동 크기 조정 및 텍스트와 숫자 모두.이 질문에 대한 답변에 영감을 받아 - https://stackoverflow.com/a/49130234/5236534
onInput = {(e) =>{
e.target.value = (e.target.value).toString().slice(0,10)
import * as React from 'react';
import TextareaAutosize from '@mui/material/TextareaAutosize';
export default function MinHeightTextarea() {
return (
<TextareaAutosize
aria-label="minimum height"
minRows={3}
placeholder="Minimum 3 rows"
style={{ width: 200 }}
onInput = {(e) =>{
e.target.value = (e.target.value).toString().slice(0,10)
}}
/>
);
}
데모 링크: MUI 텍스트 영역의 문자 길이 제한자동 크기 조정
<TextField
id="SigninTextfield"
label="Aadhaar number"
id="Aadhar"
lineDirection="center"
required={true}
type="number"
inputProps={{
maxLength: 20,
}}
style={styles.rootstyle}
erorText="Please enter only 12 digits number"
/>
아직 숫자 필드의 솔루션을 찾고 있는 분들에게 이 솔루션은 잘 작동했습니다.
onInput={(e: any) => {
e.target.value = Math.max(0, parseInt(e.target.value))
.toString()
.slice(0, 2);
}}
아무 거나 쓰세요.
언급URL : https://stackoverflow.com/questions/45939909/put-length-constraint-in-a-textfield-in-react-js
'programing' 카테고리의 다른 글
| 각도 2/4/5가 IE11에서 작동하지 않음 (0) | 2023.02.23 |
|---|---|
| 유형 [단순 유형, 클래스...]에 대한 (Map) 키 역직렬라이저를 찾을 수 없습니다. (0) | 2023.02.23 |
| div 또는 다른 방법을 사용하여 단락 텍스트와 함께 헤더를 인라인으로 표시하는 방법 (0) | 2023.02.23 |
| CosmosDB JSON with SQL - 노드에 필드가 있는지 확인합니다.JS (0) | 2023.02.23 |
| 기능적인 컴포넌트에서 React의 소품에서 제네릭스를 사용하는 방법 (0) | 2023.02.23 |