I'm trying to implement my own validator component for inputs in React native, my component receives a type of function to validate, setFunction for set("return") the result and a property for to know if is enabled.
Validator.tsx
const OnlyNumbers=(value:any, message:string="Error number format")=>{
let match=false;
if(typeof value =="number")
match=true;
if(typeof value=="string")
match= /^[0-9]*$/.test(value);
return match ? '' : message;
}
const Email=(value:string, message:string="Error email format" ):string=>{
let match=false;
match= /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value);
return match ? '' : message;
}
const Validator=(props)=>{
const {setResult, typeValidate, enable=true , defStyle={color:'red', fontSize:15}} = props;
const [text, setText] = useState('');
useEffect(()=>{
if(enable){
//to invoke received function validate
let sms = typeValidate()
setText(sms)
//returns if exists an error
setResult(sms.length>0)
}
}, [enable, setResult])
return(
<>
{enable && text.length>0 ? <Text style={defStyle}>{text}</Text>:null}
</>
);
}
export const ValidatorType={
OnlyNumbers,
Email,
}
export default Validator;
Implementation.tsx
import Validator, {ValidatorType} from '../Components/Validator'
const Implementation=(props)=>{
const [email, setEmail] = useState('');
const [telephone, setTelephone] = useState('');
const [submit, setSubmit] = useState(false);
const [errorForm, setErrorForm] =useState(false);
async function RegisterTaster(){
setSubmit(true)
if(!errorForm){
//do something.....
}
}
return(
<View>
<TextInput placeholder="Email..." defaultValue={email} onChangeText={txt=> setEmail(txt)} style={Styles.txtInputs} />
<Validator typeValidate={()=>ValidatorType.Email(email)} setResult={resp=> setErrorForm(resp)} enable={submit} defStyle={Styles.txtInputsError} />
<TextInput placeholder="Telephone..." defaultValue={telephone} onChangeText={txt=> setTelephone(txt)} style={Styles.txtInputs} />
<Validator typeValidate={()=>ValidatorType.OnlyNumbers(telephone)} setResult={resp=> setErrorForm(resp)} defStyle={Styles.txtInputsError} />
<Button primary style={Styles.btnRegister} onPress={async ()=> await RegisterTaster() }>
<Text style={Styles.txtRegister}>Register</Text>
</Button>
<View>
)
}
Actually in RegisterTaster() first, i set the submit to true for update the enable prop in each validator; i want in that moment if exists an error, the Validator update errorForm before continue to the next if for to know if do or not something...
How can i wait until the validator updates the errorForm before evaluating the next ?
I had to define a value for set the result of the specify validation like (setIsValidEmail):
<Validator typeValidate={()=>ValidatorType.Email(email)} value={email} setResult={resp=> setIsValidEmail(resp)} visible={enabledValidator} />
And in the function i ask for the result:
if(isValidEmail)
{...do something}