Search code examples
reactjsreact-nativereact-native-stylesheet

adding form validation in react-native, removing extra spaces


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?


Solution

  • 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