如何处理本机文本输入组件上的输入验证?

时间:2019-07-14 13:25:00

标签: javascript validation react-native state react-native-textinput

我正在尝试在PhoneInput组件上实现电话验证,但是我在抽象级别上有些迷茫和困惑。

我有一个由3个组成部分组成的层次结构State (custom state handler) -> Phone Form (the phone form) -> Phone Input (actual phone input)

尝试过的事情:

  1. 通过PhoneInput事件在onBlur()上进行验证, 但是 无法正确获取目标电话值;得到[object Object]circular Dependency

  2. 将验证放入State组件中, 但是 无法使我的状态正确更改

  3. 将整个PhoneInput重构为一个处理state的类,而无需使用State组件, 但是 登录表单停止工作

这不应该那么难,但是我绊倒了一些简单的东西。任何帮助将不胜感激。谢谢

期望的行为::当我输入以0开头的电话号码时,我想从该电话号码中删除该零。

代码:(我已从示例中删除了所有样式表,道具和导入,但对我想做的事情发表了评论)

State.js


...omitted_code

export default class State extends React.Component<Props> {
  state = this.props.default

  update = values => {
    // [NOTE]:  2nd Try

    // const phoneValue = values.phone
    // const beginsWithZero = /^0?/

    // if (phoneValue === beginsWithZero) {
    //   const phoneFormatValue = phoneValue.replace(beginsWithZero, '')
    //   return this.setState(phoneFormatValue)
    // } else {
    //   return this.setState(values)
    // }

    this.setState(values)

    // [NOTE]: All this works, but I cannot make the state to update with phoneFormattedValue

    // console.log(`This is the value: ${JSON.stringify(values, null, 2)}`)
    // const beginsWithZero = /^0?/
    // const phoneValue = values.phone
    // const phoneFormattedValue = phoneValue.replace(beginsWithZero, '')

    // console.log(`This is the phoneValue: ${phoneValue}`)
    // console.log(`This is the phoneFormatted: ${phoneFormattedValue}`)

    // console.log(`This is the state: ${JSON.stringify(this.state, null, 2)}`)

    // formatPhoneValue = () => {}

    this.props.onChange({ ...this.state, ...values })
  }

  render() {
    const { children } = this.props

    return children(this.state, this.update)
  }
}

State.defaultProps = {
  default: {},
  onChange: () => {},
}

PhoneForm.js

..omitted_code

const PhoneForm = ({ locale, countryCode, countryCodes, style, onChange, error }: Props) => (
  <State default={{ ...DEFAULT_FORM, countryCode }} onChange={onChange}>

    //[NOTE]: the form and the update is  what I think causes me problems

    {(form, update) => (
        <LoginField style={error ? error && styles.error : false}>
          <PhoneInput
            {...form}
            countryCodes={countryCodes}
            style={loginFieldStyles.input}
            onChangeText={update}
          />
        </LoginField>
      </View>
    )}
  </State>
)

..omitted_code

PhoneInput.js

// [NOTE]:  1st Try: trying to handle the validation inside the component itself, would like to take that phone value from `changeText({ countryCode ,phone})` and formatted onBlur

const isValidPhoneNumber = value => {
  const phoneRegex = /^0?/

  // const phoneFormated = phone.replace(phoneRegex, '')

  // const phoneStartsWithZero = phone.startsWith('0')

  // const phoneFormated = phoneStartsWithZero ? phone.replace(phoneRegex, '') : phone

  // console.log(`${phone.startsWith('0')} starts with zero.`)



  //[NOTE]: Returns either undefined or [object Object]

  console.log('This is the value.phone', value.phone)  
  console.log('This is the value', value)
  // console.log(`This is the phone that was entered phone: ${phoneFormated}`)

  // return phoneFormated
}

type PhoneInputProps = {
...omitted_code
}

const PhoneInput = ({
...omitted_code
}: PhoneInputProps) => (
  <View style={styles.host}>

    ...omitted_code

    <RNTextInput
      ...omitted_code
      value={phone}
      onChangeText={phone => onChangeText({ countryCode, phone })}
      onFocus={phone => console.log(`I was focused, this is the phone: ${phone}`)}
      onBlur={value => isValidPhoneNumber(value)}
      {...props}
    />
  </View>
)

0 个答案:

没有答案