Как установить только номер значения или для ввода текста должен быть @ в текстовом вводе React NATIVE - PullRequest
0 голосов
/ 03 марта 2020

Я хочу сделать текстовый ввод для телефонного номера, и значение должно быть только числом и иметь минимальную длину 7, а другой текстовый ввод для электронной почты, значение должно иметь «@». и если значение ввода текста телефона и электронной почты не подходит для этого условия, я хочу дать предупреждение.

<Text
  style={{
    marginTop: 10,
    marginLeft: 0,
    textAlign: 'auto',
    fontWeight: 'bold',
  }}>
  Phone Number :
</Text>

<Item>
  <Input
    placeholder=""
    style={{ fontSize: 14, borderColor: '#00468c', borderWidth: 1, marginTop: 8 }}
    placeholderTextColor='#cfcfcf'
    onChangeText={valueNoHP => {
      this.setState({ valueNoHP })
      console.log("Ini: " + valueNoHP)
    }}
    value={this.state.valueNoHP}
    keyboardType='number-pad'
    minLength={7}
  />
</Item>

<Text
  style={{
    marginTop: 10,
    marginLeft: 0,
    textAlign: 'auto',
    fontWeight: 'bold',
  }}>
  Email Address :
</Text>

<Item>
  <Input autoCapitalize='none' placeholder="" style={{ fontSize: 14, borderColor: '#00468c', borderWidth: 1, marginTop: 8 }} placeholderTextColor='#cfcfcf'
    onChangeText={valueEmail => this.setState({ valueEmail })}
    value={this.state.valueEmail}
    keyboardType='email-address'
  />
</Item>

Ответы [ 2 ]

0 голосов
/ 03 марта 2020

Я предложу реагировать-нативный TextInput do c вот ссылка, вы найдете множество свойств и методов, которые могут помочь в будущем.

https://reactnative.dev/docs/textinput

Вот рабочий пример, который действительно нужен. ссылка на выставку

https://snack.expo.io/@asad_4561 / textinput? session_id = snack-session-7_eZSvZUo & preview = true & platform = web & iframeId = 33hlricz7f & supportPlatforms = ios, android, web & name = TextInput & description = ExampleD0DataText & waitFor

код здесь (вы можете изменить в соответствии с вашими потребностями)

import React, { Component } from 'react';
import { View, Text,TextInput,Alert } from 'react-native';

export default class  App extends Component{ 
  constructor(props) 
  {
      super(props);
      this.FocusToPhone = null;
      this.FocusToEmail = null; 
      this.state={
        phone:0,
        email:"",
      };
  }
  onChangeEmail(text){
    this.setstate({email:text});
  }
  onChangephone(text){
    if(text.length < 7)
    {
      Alert.alert ('Alert', 'Phone number length is too small! please re-enter phone number');
      this.FocusToPhone.focus();
    }
    else
    {
      this.setstate({phone:text });
      this.FocusToEmail.focus();
    }  
  }
render()
    {
return (
    <View>
        <Text
      style={{
        marginTop: 10,
        marginLeft: 0,
        textAlign: 'auto',
        fontWeight: 'bold',
      }}>
      Phone Number :
    </Text>
        <TextInput
          ref={(input) => { this.FocusToPhone = input; }}
          style={{ height: 40, borderColor: 'gray',borderWidth: 1 }}
          onSubmitEditing={e => this.onChangephone(e.nativeEvent.text)}
          autoCapitalize='none'
          autoCorrect={false}
          enablesReturnKeyAutomatically={true}
          keyboardType={"phone-pad"}
          placeholder="Phone #"
        />

    <Text
    style={{
      marginTop: 10,
      marginLeft: 0,
      textAlign: 'auto',
      fontWeight: 'bold',
    }}>
    Email Address :
  </Text>
        <TextInput
         ref={(input) => { this.FocusToEmail = input; }}
          placeholder="Email"
          style={{ height: 40, borderColor: 'gray',borderWidth: 1 }}
          autoCapitalize='none'
          autoCorrect={false}
          enablesReturnKeyAutomatically={true}
          onChangeText={text => this.onChangeEmail(text)}
          //value={value}
          keyboardType={"email-address"}
        />

    </View>

  );
}

}
0 голосов
/ 03 марта 2020

В onChangeText вы можете поставить любую функцию. Так что вы можете проверить длину со стандартным javascript материалом. С точки зрения дизайна, вероятно, проще иметь только одну функцию, которая вызывается с onChangeText, которая проверяет состояние после установки.

...