adding form validation in react-native, removing extra spaces

665 views Asked by At

I have a login form that looks like this (1): enter image description here

when I add form validation it looks like this (2): enter image description here

the spcaes between the textInputs are because I have something like this:

    <View style={styles.SectionStyle}>
      <TextInput
        style={styles.inputStyle}
        .
        .
        .
        onBlur={() => checkEmailRGX()}
      />
    </View>
    <View style={styles.ErrorStyle}><Text style={{color: 'red', fontWeight: 'bold'}}>{emailError}</Text></View>

when the inputs are incorrect (3): enter image description here

I want to keep the form the same as (1), when fields are not correctly filled in then it goes to (3), and when any of the fields are filled in correctly, the error text should be gone, plus the area the stay at and when you start the form there is a gap between the elements of the form and it looks like (2),

this is my error text field:

  var emailErrorField = '';

and this is the validation:

const checkEmailRGX = () => {
    let rjx=/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
    let isValid = rjx.test(email);
    if(email == ''){
      emailErrorField = t('eptyfield');
      setEmailErro(emailErrorField);
    }
    else if(!isValid){
      emailErrorField = t('emailfield');
      setEmailErro(emailErrorField);
    }
    else{
      emailErrorField = "";
      setEmailErro(emailErrorField);
    }
  }

How can I remove the white spaces but keep the error message?

2

There are 2 answers

6
Guruparan Giritharan On BEST ANSWER

Conditionally render the error like below

{
emailErrorField && <View style={styles.ErrorStyle}><Text style={{color: 'red', fontWeight: 'bold'}}>{emailError}</Text></View>
}

Then it would be shown only if emailError has value

0
AntonioSk On

trim the input with: string.trim()

In JavaScript, trim() is a string method that is used to remove whitespace characters from the start and end of a string. Whitespace characters include spaces, tabs, etc. Because the trim() method is a method of the String object, it must be invoked through a particular instance of the String class

Then check if string is null or ""