Reputation: 493
I'm new to JQuery and wrote a simple validation to check the email address. But it is not working as expected. Can someone suggest to fix this?
<script>
$( "#email" ).blur(function() {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if($( "#Email" ).val().match(mailformat))
{
alert("You have entered an valid email address!");
}
else
{
alert("You have entered an invalid email address!");
}
});
</script>
</head>
<body>
<label for="email" id="email-ariaLabel">Your email address:</label>
<input id="email" name="email" type="email" class="required" title="This is a required field" /> <span class="msg error">Not a valid email address</span>
<span class="msg success">A valid email address!</span>
Upvotes: 0
Views: 262
Reputation: 308
You can refer the code below it will solve Ur problem.
<script>
$( "#email" ).blur(function() {
var mailformat = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var emailTextField = $( "#email" ).val();
if(!emailReg.test(emailTextField) || emailTextField.length == 0)
{
alert("You have entered an invalid email address!");
}
else
{
alert("You have entered an valid email address!");
}
});
</script>
Upvotes: 0
Reputation: 189
Try this -
<script>
$( "#email" ).blur(function() {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if($( "#email" ).val().match(mailformat))
{
alert("You have entered an valid email address!");
}
else
{
alert("You have entered an invalid email address!");
}
});
</script>
</head>
<body>
<label for="email" id="email-ariaLabel">Your email address:</label>
<input id="email" name="email" type="email" class="required" title="This is a required field" /> <span class="msg error">Not a valid email address</span>
<span class="msg success">A valid email address!</span>
or you can simply use data annotation for email
as
[StringLength(100, ErrorMessage = "Email can accept maximum 100 characters.")]
[RegularExpression("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+(?:[a-zA-Z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$", ErrorMessage = "Please enter valid email address.")]
public string email { get; set; }
Upvotes: 1
Reputation: 43166
Your code will run before the elements are created, so the handler won't be attached. You should wrap your code in $(document).ready()
so that the code runs after the elements are created.
Also, selectors are case sensitive you should use $("#email").val()
instead of $("#Email").val()
$(document).ready(function(){
$( "#email" ).blur(function() {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if($("#email").val().match(mailformat))
{
alert("You have entered an valid email address!");
}
else
{
alert("You have entered an invalid email address!");
}
});
})
Upvotes: 2