0
\$\begingroup\$

Problem statement

Write an anonymous function which take email address as parameter and returns true/false after validating the input parameter.

Objective

This assignment will help you to master the following concepts:

  • function

  • closures


Solution

<!DOCTYPE html>
<html>
    <head>
        <title>Anomymous function</title>
        <meta charset="UTF-8">
        <script type="text/javascript">
            var result = (function(email_id){
                            var regpat = /^[a-zA-Z_\.\-]+@[a-zA-Z_\-\.]+?\.[a-zA-Z]{2,4}$/;
                            return regpat.test(email_id);
                        })('[email protected]');
            document.write(result);
        </script>
    </head>
    <body>

    </body>
</html>

1) Is this the corresponding solution?

2) Why document.body.innerHTML = result; does not work?

\$\endgroup\$
0

2 Answers 2

7
\$\begingroup\$

As I already noted in your other question, trying to validate email addresses correctly is an almost impossible task; there are a lot more characters allowed that you are assuming. Check out this correct regex to validate addresses, which is quite unpractical.

This means that we can either be too strict or too lenient with our regex. For front-end validation, being too strict is not the right choice as people with valid email addresses will not be able to use your service.

Personally, I would check if there is an @ in the string, and be done with it. It will catch common typos, there isn't much more you can do.

Later on, you could write two functions: requiredEmailValidation and optionalEmailValidation. The first just looks for an @, and doesn't allow a form to be submitted, the second checks for common typos (eg .con instead of .com, gmai.com instead of gmail.com, etc) and shows a warning.

Misc

  • js variable names generally can't contain -. I'm surprised it's even working for you, it didn't for me with firefox or chrome.
  • regpat isn't that great of a variable name; it's hard to read (regexPattern would be better), and contains few information (I can already see that it's a regex pattern). Something like emailPattern would be better (for such a short function, it's not that important, but if you write larger functions later on, naming becomes very important).
\$\endgroup\$
1
\$\begingroup\$

1) looks like solution

2) it is not working because you are modifying dom when it is not loaded/ready yet, so move script tag after body (or inside) and it should work (or if you are using jquery use $(function(){//your code}))

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.