Search code examples
react-nativegoogle-chromegithubstack-overflow

How to add 2 letter in capital and numeric in textinput react native


How to Add two capital alpha and 7 numeric value in textInput React native.

            <NumericTextInput
              label={'Pet License Number'}
              keyboardType="number-pad"
              // err1={errorData?.license ? true : false}
              value={license ? license : ''}
              mode={'outlined'}
              onChangeText={(val) => setLicense(val)}
              maxLength={9}
            />

This is the code and format is MD2345133


Solution

  • Try this regular expression that will helpful to validate input to only accept string with two capital alphabets and 7 numeric values:

    ^([A-Z]{2}\d{7})$
    

    For example:

    const App = () => {
      const [text, setText] = useState('');
      const [isValid, setIsValid] = useState();
    
      const handleChange = (event) => {
        const value = event.nativeEvent.text;
        const regex = /^[A-Z]{2}\d{7}$/;
        setText(value);
        if (regex.test(value)) {
          setIsValid(true);
        } else {
          setIsValid(false);
        }
      };
    
      return (
        <View>
          <TextInput
            placeholder="Enter two capital letters and 7 digits"
            onChange={handleChange}
            value={text}
          />
          {!isValid && <Text>Input string is not valid</Text>}
        </View>
      );
    };