본문 바로가기
Front-end/React\RN

리액트네이티브, 입력 검증

by javapp 자바앱 2023. 8. 8.
728x90

 

 

StartGameScreen.js

import { TextInput, View , StyleSheet, Alert} from 'react-native';

import PrimaryButton from '../components/PrimaryButton';
import { useState } from 'react';
function StartGameScreen() {

  const [enteredNumber, setEnteredNumber] = useState('');

  function numberInputHandler(enteredText) {
    setEnteredNumber(enteredText);
  }

  function resetInputHandler() {
    setEnteredNumber('')
  }

  function confirmInputHandler() {
    const chosenNumber = parseInt(enteredNumber);
    if(isNaN(chosenNumber) || chosenNumber <= 0 || chosenNumber > 99) {
      Alert.alert(
        '메시지',
        '입력을 확인해주세요.',
        [{text: '확인', style: 'destructive', onPress: resetInputHandler}]) // 버튼으로 넘김
      return;
    }
  }
 
return (
    <View style={styles.inputContainer}>
      <TextInput
        style={styles.numberInput}
        maxLength={2}
        keyboardType='number-pad'
        autoCapitalize='none'
        autoCorrect={false}
        value={enteredNumber}
        onChangeText={numberInputHandler}
        />
      <View style={styles.buttonsContainer}>
        <View style={styles.buttonContainer}>
          <PrimaryButton onPress={resetInputHandler}>취소</PrimaryButton>
        </View>
        <View style={styles.buttonContainer}>
          <PrimaryButton onPress={confirmInputHandler}>확인</PrimaryButton>
        </View>
      </View>
    </View>
  );
}
...

confirmInputHandler 에서 한글로 변환 후

숫자로 변환되었는지 검증

isNaN(..) : 숫자가 아니면 true 

앱 자체 API Alert 사용

 

 

PrimaryButton

import { View, Text , Pressable, StyleSheet} from 'react-native';

function PrimaryButton({ children, onPress }) {
 
  return (
      <View style={styles.buttonOuterContainer}>
        <Pressable style={({pressed}) =>
        pressed ? [styles.buttonInnerContainer, styles.pressed] : styles.buttonInnerContainer}
        onPress={onPress} android_ripple={{color: '#640233'}}>
      {/* props.children */}
        <Text style={styles.buttonText}>{children}</Text>  
        </Pressable>
      </View>
  );
}

export default PrimaryButton;
...
...
 

PrimaryButton 에서 입력이 되면 onPress 실행

onPress로 넘어온 resetInputHandler 실행

 

 

 

 

 

 

 

 

 

 

 

 

 

 

댓글