숫자 만 허용하는 React Native TextInput
TextInput숫자 (0-9) 만 입력 할 수 있는 React Native 구성 요소 가 필요합니다 . 나는 설정할 수 keyboardType에 numeric거의 기간을 제외하고 입력 저를 얻을 수있는을 (.). 그러나 이것은 숫자가 아닌 문자를 필드에 붙여 넣는 것을 중단하지 않습니다.
지금까지 내가 생각 해낸 것은 OnChangeText이벤트를 사용하여 입력 된 텍스트를 보는 것입니다. 텍스트에서 숫자가 아닌 문자를 제거합니다. 그런 다음 상태 필드에 텍스트를 입력합니다. 그런 다음 업데이트 TextInput그것의를 통해 Value속성입니다. 아래 코드 스 니펫.
<TextInput
style={styles.textInput}
keyboardType = 'numeric'
onChangeText = {(text)=> this.onChanged(text)}
value = {this.state.myNumber}
/>
onTextChanged(text) {
// code to remove non-numeric characters from text
this.setState({myNumber: text})
}
이것은 작동하는 것처럼 보이지만 해킹처럼 보입니다. 이를 수행하는 다른 방법이 있습니까?
이는 그러한 구성 요소 (또는 TextInput의 속성)가 특별히 개발 될 때까지이를 수행하는 올바른 방법입니다.
웹에는 입력 요소에 대한 '숫자'유형이 있지만 웹 기반이며 react-native는 웹보기를 사용하지 않습니다.
해당 입력을 자체적으로 반응 구성 요소로 만드는 것을 고려할 수 있습니다 (NumberInput 호출 일 수 있음) : 다른 값 필터 / 체커를 가진 많은 TextInput을 만들 수 있기 때문에이를 재사용하거나 오픈 소스로 만들 수 있습니다.
즉각적인 수정의 단점은 자신의 가치에 어떤 일이 일어 났는지에 대한 혼란을 방지하기 위해 사용자에게 올바른 피드백을 제공하는 것입니다.
이렇게 할 수 있습니다. 숫자 값만 허용되며 원하는대로 10 개 숫자로 제한됩니다.
<TextInput
style={styles.textInput}
keyboardType='numeric'
onChangeText={(text)=> this.onChanged(text)}
value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
페이지에 다음 코드를 작성하여 입력 된 값을 볼 수 있습니다.
{this.state.myNumber}
onChanged () 함수에서 코드는 다음과 같습니다.
onChanged(text){
let newText = '';
let numbers = '0123456789';
for (var i=0; i < text.length; i++) {
if(numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
}
else {
// your call back function
alert("please enter numbers only");
}
}
this.setState({ myNumber: newText });
}
다른 사람들에게 도움이되기를 바랍니다.
RegExp를 사용하여 숫자가 아닌 것을 대체하는 것이 다른 답변과 마찬가지로 화이트리스트와 함께 for 루프를 사용하는 것보다 빠릅니다.
onTextChange 핸들러에 이것을 사용하십시오.
onChanged (text) {
this.setState({
mobile: text.replace(/[^0-9]/g, ''),
});
}
성능 테스트 : https://jsperf.com/removing-non-digit-characters-from-a-string
React Native TextInput은 다음 가능한 값으로 keyboardType 소품을 제공합니다. 기본 숫자 패드 십진수 패드 숫자 이메일 주소 전화 패드
따라서 귀하의 경우에는 숫자 만 받아들이 기 위해 keyboardType = 'number-pad'를 사용할 수 있습니다. 여기에는 '.'가 포함되지 않습니다.
그래서,
<TextInput
style={styles.textInput}
keyboardType = 'number-pad'
onChangeText = {(text)=> this.onChanged(text)}
value = {this.state.myNumber}
/>
귀하의 경우에 사용해야하는 것입니다.
자세한 내용은 TextInput에 대한 공식 문서 링크를 참조하십시오 : https://facebook.github.io/react-native/docs/textinput#keyboardtype
정규식을 사용하는 숫자 만 허용
<TextInput
keyboardType = 'numeric'
onChangeText = {(e)=> this.onTextChanged(e)}
value = {this.state.myNumber}
/>
onTextChanged(e) {
if (/^\d+$/.test(e.toString())) {
this.setState({ myNumber: e });
}
}
둘 이상의 유효성 검사를 원할 수 있습니다.
<TextInput
keyboardType = 'numeric'
onChangeText = {(e)=> this.validations(e)}
value = {this.state.myNumber}
/>
numbersOnly(e) {
return /^\d+$/.test(e.toString()) ? true : false
}
notZero(e) {
return /0/.test(parseInt(e)) ? false : true
}
validations(e) {
return this.notZero(e) && this.numbersOnly(e)
? this.setState({ numColumns: parseInt(e) })
: false
}
입력을 확인하는 기능 :
validateInputs(text, type) {
let numreg = /^[0-9]+$/;
if (type == 'username') {
if (numreg.test(text)) {
//test ok
} else {
//test not ok
}
}
}
<TextInput
onChangeText={text => this.validateInputs(text, 'username')}
/>
I hope this is helpful.
A kind reminder to those who encountered the problem that "onChangeText" cannot change the TextInput value as expected on iOS: that is actually a bug in ReactNative and had been fixed in version 0.57.1. Refer to: https://github.com/facebook/react-native/issues/18874
<TextInput autoCapitalize={'none'} maxLength={10} placeholder='Mobile Number' value={this.state.mobile} onChangeText={(mobile) => this.onChanged(mobile)}/>
and onChanged method :
onChanged(text){
var newText = '';
var numbers = '0123456789';
if(text.length < 1){
this.setState({ mobile: '' });
}
for (var i=0; i < text.length; i++) {
if(numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
}
this.setState({ mobile: newText });
}
}
I had the same problem in iOS, using the onChangeText event to update the value of the text typed by the user I was not being able to update the value of the TextInput, so the user would still see the non numeric characters that he typed.
This was because, when a non numeric character was pressed the state would not change since this.setState would be using the same number (the number that remained after removing the non numeric characters) and then the TextInput would not re render.
The only way I found to solve this was to use the keyPress event which happens before the onChangeText event, and in it, use setState to change the value of the state to another, completely different, forcing the re render when the onChangeText event was called. Not very happy with this but it worked.
if (!/^[0-9]+$/.test('123456askm')) {
consol.log('Enter Only Number');
} else {
consol.log('Sucess');
}
Using a RegExp to replace any non digit. Take care the next code will give you the first digit he found, so if user paste a paragraph with more than one number (xx.xx) the code will give you the first number. This will help if you want something like price, not a mobile phone.
Use this for your onTextChange handler:
onChanged (text) {
this.setState({
number: text.replace(/[^(((\d)+(\.)\d)|((\d)+))]/g,'_').split("_"))[0],
});
}
I wrote this function which I found to be helpful to prevent the user from being able to enter anything other than I was willing to accept. I also used keyboardType="decimal-pad" and my onChangeText={this.decimalTextChange}
decimalTextChange = (distance) => { let decimalRegEx = new RegExp(/^\d*\.?\d*$/) if (distance.length === 0 || distance === "." || distance[distance.length - 1] === "." && decimalRegEx.test(distance)){ this.setState({distance}) } else { const distanceRegEx = new RegExp(/^\s*-?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/) if ( distanceRegEx.test(distance)) this.setState({distance}) } }
The first if block is error handling for the event the user deletes all of the text, or uses a decimal point as the first character, or if they attempt to put in more than one decimal place, the second if block makes sure they can type in as many numbers as they want before the decimal place, but only up to two decimal places after the point.
This not work on IOS, setState -> render -> not change the text, but can change other. The textinput can't change itself value when textOnChange.
by the way, This work well on Android.
I've created a component that solves this problem:
https://github.com/amirfl/react-native-num-textinput
You can remove non numeric characters using regex
onTextChanged (text) {
this.setState({
myNumber: text.replace(/\D/g, ''),
});
}
Here is my other simple answer to accept only numbers in the text box using Regular Expressions.
onChanged(text){
this.setState({
myNumber: text.replace(/[^0-9]/g, '')
});
}
For Decimal /Floating point number only try this
onChangeMyFloatNumber(text){
let newText = '';
let numbers = '0123456789.';
for (var i=0; i < text.length; i++) {
if(numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
if(text[i]=="."){
numbers = '0123456789'
}
}
else {
// your call back function
alert("please enter numbers only");
}
}
this.setState({ MyFloatNumber: newText });
}
'programing tip' 카테고리의 다른 글
| CSS3가 글꼴 크기를 전환 할 수 있습니까? (0) | 2020.11.13 |
|---|---|
| 하위 디렉터리를 포함하여 디렉터리에서 모든 0 바이트 파일을 찾는 방법 (0) | 2020.11.13 |
| JQuery-전역 변수에 ajax 응답 저장 (0) | 2020.11.13 |
| jQuery로 텍스트를 변경하는 방법 (0) | 2020.11.13 |
| 특정 div의 거터 공간 만 제거 (0) | 2020.11.13 |