Reputation: 431
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?
Upvotes: 2
Views: 61
Reputation: 1793
YOU HAVE PASSED EVENT OBJECT AT THE WRONG FUNCTION. JS CODE
$(document).ready(function() {
$('#validate').click(function(e) {
var sEmail = $('#email').val();
if ($.trim(sEmail) === '') {
alert('Please enter valid email address');
e.preventDefault();
} else if (validateEmail(sEmail)) {
alert("email is fine");
} else {
alert('Invalid Email Address');
e.preventDefault();
}
});
});
function validateEmail(sEmail) {
var filter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
HTML CODE
<input type='email' id='email'>
<button id='validate'>Validate</button>
Upvotes: 1
Reputation: 9680
There are few thing you need to do.
Upvotes: 1
Reputation: 8042
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>
Upvotes: 1
Reputation: 1691
Try by return false statement in validate click event
$(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)) {
return true;
}
else {
alert('Invalid Email Address');
//e.preventDefault();
return false;
}
});
});
Hope this help.
Upvotes: 1