Reputation: 565
I want to use Function name whose name is as per concatenating strings and variable.
validate contains the Function Name:
const validate='validate'+type.replace(/^./, type[0].toUpperCase());
where type='email'
const validateEmail = (e) => {
email=e.target.value;
//console.log(email);
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
{(!re.test(email)) && console.log("Please enter a valid email address");}
}
Now I want to use this validate as the function name in onBlur
onBlur={validate}
in
<input onChange={handleChange} onBlur={validate} />
Warning: Expected onBlur
listener to be a function, instead got a value of string
type.
Upvotes: 0
Views: 135
Reputation: 4770
You can have a generic function like this, which takes type as input and returns a validating function.
const createValidator = type => {
switch (type) {
case 'email':
return (event) => {
const email = event.target.value;
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
(!re.test(email)) && console.log("Please enter a valid email address");
}
default:
return null;
}
}
And in your input tag, you can use it like this
<input onChange={handleChange} onBlur={createValidator('email')} />
Upvotes: 1