I'm fairly new to JS & React and I'm using React Hook Form I have to check if the Website entered into the Website field in my form exists or not. If the URL doesn't exist I have to show an error message as "Website not available" under the Website field which will get rendered using a FormError component.
(This is a First Name field but since I'm using a common TextField Component it should work here as well)
So, I'm using "url-exists" package to test if a website URL exists and if the website doesn't exists it should generate an error as "Website not available".
I'm using this code to implement.
const websiteCheck = (value) => {
let str = value;
let message = "";
let urlCheck = str.indexOf("http://") == 0 || str.indexOf("https://") == 0;
if (!urlCheck) {
console.log("Protocol doesn't exist!");
str = "http://" + str;
} else {
console.log("Protocol exists!");
}
urlExists(str, function (err:any, exists:any) {
if (!exists) {
message = "Website doesn't exists!" //Just for testing
console.log("Not available: ", str, exists);
} else {
message = "Website exists!"
console.log("Available: ", str, exists);
}
// console.log(exists); // true
});
return message;
}
And I'm calling it as :
return(
.....
<TextField
key={fieldName}
id={fieldName}
.......
inputRef={register({
websiteCheck(value)
........
/>
This should ideally work but it's giving me "Not available" message in console.log() even if I enter a correct & valid URL. And it still won't render the message I set.
What I found so far from debugging is :
What should I do to get this resolved?
You have to correct a few things here to make it work:
<Controller />
when using a Material UI <TextField />
, see this section in the docs for more infos about itvalidate
function provided by RHF via the rules
prop of the <Controller />
, check here for all validation options (register
and rules
use the same interface for validations)urlExists
uses a callback, so you need to wrap the call to urlExists
into a Promise
and set it as the return value of your websiteCheck
function. Right now you are returning a string before the callback is even executed. The important thing here is to also make your websiteCheck
function async
, so that the Promise will get resolved (the validate
function from RHF supports using a async
function)true
for the validate
function if the entered value is correct. If not use a string for the error messageCollected from the Internet
Please contact [email protected] to delete if infringement.
Comments