Search code examples
javascripthtmlvalidationemail-validation

Handling HTML types 'email', 'url' with JavaScript


Having

<input type="email" name="myEmail" />

I would like to inform JavaScript whether the entered input is en e-mail or not. Same thing with 'url' and other HTML input types.

Is there any 'flag' or whatsoever that signals if the HTML type requirement has been fulfilled?


Solution

  • You could use the required parameter:

    <input type="email" required>
    

    So it will use the browser check for email, but actually it's not perfect. Something like asd@asd is valid even if you didn't wrote the TLD.

    You also could use the pattern parameter parameter to use Regular Expressions.

     <input type="email" required pattern="[a-zA-Z0-9-_]*@[a-zA-Z0-9-_]*\.[a-z]{2,4}">
    

    (Carefull this RegEx is mostly wrong/bad)

    But actually you are aiming to the newer browsers and not every browser will have this functions.

    The best way would be to use Javascript to do a validation with a Regular Expression like the one I allready wrote. You should search for an Expression that fits for your requirements, because there are a lot of Expressions in the internet.

    Don't forget that everything that happens on the clientside can be exploitet. With Chrome you just need to hit F12 and change the Javascript Part for checking the validation. To be sure, you also should do a RegEx inside your serverside script.

    The Javascript and Serverside check (like with PHP) should work in the most browsers, because the browser doesn't care about Serverside activities and Javascript existst since IE1 (?) or at least since at the early ages of browsers.