Nick Tirrell Nick Tirrell - 7 months ago 21
HTML Question

jQuery Email Validator - Implementation Issue?

I have a script to validate the "email" field in a form when the "submit" button is clicked, and everything is working just dandy on jsfiddle, but when I implement the script in the head like so...

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
$(document).ready(function(e) {
$('#validate').click(function() {
var sEmail = $('#mail').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (validateEmail(sEmail)) {
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
});

function validateEmail(sEmail) {
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
</head>


well, nothing happens. :(

What the heck am I doing wrong here?

Answer

You have to create a separate tag for the embedded code. Try this:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
<script type="text/javascript>
    $(document).ready(function(e) {
        $('#validate').click(function() {
            var sEmail = $('#mail').val();
            if ($.trim(sEmail).length == 0) {
                alert('Please enter valid email address');
                e.preventDefault();
            }
            if (validateEmail(sEmail)) {
            }
            else {
                alert('Invalid Email Address');
                e.preventDefault();
            }
        });
    });

    function validateEmail(sEmail) {
        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        if (filter.test(sEmail)) {
            return true;
        }
        else {
            return false;
        }
    }
</script>
</head>