How apply this validator functions to my Textinput?

Hi, I’m new in React Native and I need put these functions connected to a Text input for a form that will add records to a database.

The functions:


function clean (rutdni) {
  return typeof rutdni === 'string'
    ? rutdni.replace(/^0+|[^0-9kK]+/g, '').toUpperCase()
    : ''
}

function validate (rutdni) {
  if (typeof rutdni !== 'string') {
    return false
  }

  // if it starts with 0
  if (/^0+/.test(rutdni)) {
    return false
  }

  if (!/^0*(\d{1,3}(\.?\d{3})*)-?([\dkK])$/.test(rutdni)) {
    return false
  }

  rutdni = clean(rutdni)

  let t = parseInt(rutdni.slice(0, -1), 10)
  let m = 0
  let s = 1

  while (t > 0) {
    s = (s + (t % 10) * (9 - (m++ % 6))) % 11
    t = Math.floor(t / 10)
  }

  const v = s > 0 ? '' + (s - 1) : 'K'
  return v === rutdni.slice(-1)
}

function format (rutdni) {
  rutdni = clean(rutdni)

  let result = rutdni.slice(-4, -1) + '-' + rutdni.substr(rutdni.length - 1)
  for (let i = 4; i < rutdni.length; i += 3) {
    result = rutdni.slice(-3 - i, -i) + '.' + result
  }

  return result
}

function getCheckDigit (input) {
  const rutdni = Array.from(clean(input), Number)

  if (rut.length === 0 || rutdni.includes(NaN)) {
    throw new Error(`"${input}" as INVALID`)
  }

  const modulus = 11
  const initialValue = 0
  const sumResult = rutdni
    .reverse()
    .reduce(
      (accumulator, currentValue, index) =>
        accumulator + currentValue * ((index % 6) + 2),
      initialValue
    )

  const checkDigit = modulus - (sumResult % modulus)

  if (checkDigit === 10) {
    return 'K'
  } else if (checkDigit === 11) {
    return '0'
  } else {
    return checkDigit.toString()
  }
}

module.exports = { validate, clean, format, getCheckDigit }

My TextInput:

              <View style={styles.inputGroup}>
                <TextInput placeholder="  RUTDNI" keyboardType="numeric" maxLength={10} placeholderTextColor="#869AD6" onChangeText={(val) => this.setState({ nro_cedula: val })} value={this.state.nro_cedula} />
              </View>

I don’t know if I should call a file or put this in my code, if write “OnChange” or other event, I wanna that once the writing into the input is finished, show a message or put the input in red warning that the content is invalid.

(If don’t understand my english, I’m sorry, I’m not english speaker, my english is basic :C )

If you want to run it once writing is finished you can use onBlur

1 Like

Thanks, and how connect that functions with my ? I’m new in react native and programming apps for Android/iOs and these and those are the functions that I need to implement :c

<View style={styles.inputGroup}>
 <TextInput placeholder="  RUTDNI" keyboardType="numeric" maxLength={10} placeholderTextColor="#869AD6" onChangeText={(val) => this.setState({ nro_cedula: val }), **function clean**} value={this.state.nro_cedula} onBlur={(**function validate**)} />
</View>