Reputation: 531
I have this sample:
CODE HTML:
<input type="text" name="email" class="email" placeholder="Your email address">
CODE JS:
$(document).ready(function ($) {
function validateEmail(email) {
var re = /\S+@\S+\.\S+/;
return re.test(email);
}
var email = $(".email").val();
if (validateEmail(email)) {
alert("correct format");
}else{
alert("icorrect format");
}
});
Code validation above does not work properly.
Can you tell me please what is the problem? Any data is entered in the input does not check properly
Thanks in advance!
Upvotes: 0
Views: 3098
Reputation: 175
$(function(){
$('#txtEmail').on('input', function () {
console.log(validateEmail($(this).val()));
})
})
function validateEmail(email) {
var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtEmail" type="text" name="email" class="email" placeholder="Your email address">
try this one.... type email it's return true otherwise it return false.
Upvotes: 1
Reputation:
$(document).ready(function($) {
function validateEmail(email) {
var re = /^(([a-zA-Z0-9]+)|([a-zA-Z0-9]+((?:\_[a-zA-Z0-9]+)|(?:\.[a-zA-Z0-9]+))*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-zA-Z]{2,6}(?:\.[a-zA-Z]{2})?)$)/;
return re.test(email);
}
var email = $(".email").val();
if (validateEmail(email)) {
console.log("correct format");
} else {
console.log("icorrect format");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="email" class="email" value="[email protected]" placeholder="Your email address">
Check this above snippet.
Upvotes: 1
Reputation: 175
Why dont just use
<input type="email" name="email">
? It can validate too.
Upvotes: 0
Reputation: 1199
If you want simple and built-in check. I would recommend type="email"
. However, beware that this is not fully supported everywhere. More info here
Upvotes: 0