0

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?

skiwi
  • 66,971
  • 31
  • 131
  • 216
  • Is this any help? http://stackoverflow.com/questions/7548612/triggering-html5-form-validation – Lauri Elias Dec 06 '13 at 11:56
  • @LauriElias Sadly not, I want the result of the `event.target.checkValidity()`, I don't want it to throw custom error messages at the screen or anything. – skiwi Dec 06 '13 at 12:00

1 Answers1

3

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("test@email.com"));

Here is a demo.

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.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Does that only work on `:input` elements, and not on strings? – skiwi Dec 06 '13 at 12:01
  • Added a demo to show how it works. `emailAddress` should be a string parameter. – CodingIntrigue Dec 06 '13 at 12:02
  • +1. What would complete this, would be combining those two methods. Add a control statement to check the arguments type and voila... one method to rule all email validation. Be it a string, or input. I think I'll pinch your examples for future use :) – Ian Brindley Dec 06 '13 at 12:10
  • I can't seem to get it work for jQuery input elements though. `.checkValidity` gives a `TypeError` and `.checkValidity()` returns `undefined`. I think you need to use the proto part if that's the case? Not sure how it works there though. – skiwi Dec 06 '13 at 12:13
  • 1
    @skiwi It needs an HTML element. So to get that from jQuery you can use .get(): `isInputValid($("#emailInput").get());` – CodingIntrigue Dec 06 '13 at 12:51