Reputation: 69349
I know it is possibly to use the default browser validation for forms, when making custom form submit
:
event.target.checkValidity();
That does the trick.
However now, I want to validate an email that is not in the form yet, and check whether it is an email or not. I prefer not to use regex, but use the in-built browser validation, just like it does with event.target.checkValidity()
.
Any clue how I can call the function that checkValidity()
uses underlying to check whether an email is correct or not?
Upvotes: 0
Views: 632
Reputation: 78565
You could create a dynamic element and use its checkValidity
method?
function isEmailValid(emailAddress) {
var email = document.createElement("input");
email.type = "email";
email.value = emailAddress;
return email.checkValidity();
}
console.log(isEmailValid("[email protected]"));
Or if you want to test an existing input element:
function isInputValid(input) {
return input && input.checkValidity && input.checkValidity();
}
console.log(isInputValid(document.getElementById("userEmail")));
It's worth noting that checkValidity()
returns true for an empty e-mail address. So if you need it to be non-empty, you'll need to check that yourself.
Upvotes: 3