Regular expression for email not working - javascript

I am putting validation on email field but it shows error of invalid even where the email is typed in correct format.
Screenshot
Code
<script type="text/javascript">
function formvalidate(){
var email=document.signup_form.email.value;
var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$");
if(email=="")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
</script>
Thanks

try this function
function validateEmail(elementValue) {
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
Please refer this fiddle : http://jsfiddle.net/gabrieleromanato/Ra85j/

1- Use this regular expressions instead
\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
2- Change this if (!check_email.test(email)) to
if (check_email.test(email))

Try this fuction
function isEmail(inputString) {
var regExpEmail = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
try {
return regExpEmail.test(inputString.value);
}
catch (e) {
return false;
}
}

Change var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$"); to
a function like this:
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email);
}

You regex is not correct, there are many things that you've not considered, like your regex accepts only capital letters, to include both capital and small letters you should use :
[a-zA-Z0-9]
not this :
[A-Z0-9]
You can use this regex for validating email :
/^(([^<>()\[\]\\.,;:\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,}))$/
read this for details

Source and some tests
You can use this regex for email:
RegExp('\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b', 'i')

try this example : email validation using JQuery
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
function validate() {
$("#emailvalidate").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#emailvalidate").text(email + " is valid");
$("#emailvalidate").css("color", "green");
} else {
$("#emailvalidate").text(email + " is not valid");
$("#emailvalidate").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='submit' id='btn'>Validate</button>
</form>
<h2 id='emailvalidate'></h2>

Try this code -
function formvalidate()
{
var email = document.signup_form.email.value;
var check_email = RegExp("^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$", 'ig');
if(email == "")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
<form name="signup_form">
<input type="text" name="email" value="" />
<input type="button" name="validate" value="Validate" onclick="formvalidate()"/>
</form>

I am using below regex to validate email pattern. Regex is not 100% solution to validate an email, better use email verification. Regex can help to validate format or pattern only.
Jsfiddle: DEMO
Jsfiddle: Regex check and sample email DEMO
function validateEmail(elementValue) {
document.getElementById('error').innerHTML = elementValue + ', email is incorrect';
var emailPattern = /^[a-z0-9](?:[a-z0-9]+\.)*(?!.*(?:__|\\.\\.))[a-z0-9_]+#(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9](?!$)){0,61}[a-zA-Z0-9]?)|(?:(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])))$/;
if (emailPattern.test(elementValue)) {
document.getElementById('error').innerHTML = elementValue + ', email is correct';
}
return false;
}
#error {
color: red;
font-size: 2rem;
}
input[type='email'] {
padding: 5px;
width: 300px;
border-color: blue;
font-size: 16px;
}
<form name="signup_form">
<input type="email" value="" onblur="validateEmail(this.value)">
<br />
<lable id="error"></lable>
</form>

Change your regular expression to below
^[a-zA-Z0-9._-]+#[A-Za-z0-9.-]+\.[a-zA-Z0-9.-]+$
Hope this helps :)

Related

Alert box doesn't appear on matched/mismatched regex?

I made a regex to validate potential bitcoin addresses, now when I click the button for a quote I want the value entered in the form to get checked against the regex but it doesn't work.
https://jsfiddle.net/arkqdc8a/5/
var walletCheck = $('#wallet').val();
var reg = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
$('#button1').on('click', function() {
if (reg.test(walletCheck)) == false {
alert("Inalid Address");
}
else {
alert("Valid Address");
}
}
<input type="form"
id="wallet"
maxlength="34"
pattern="^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
placeholder="Your Bitcoin wallet's address"></input><br><br>
<button id="button1">Click for a quote!</button>
Try this. You had some braces not closing properly and your equality check wasn't being done correctly either. Your fiddle didn't have jQuery imported as well.
var reg = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
$('#button1').on('click', function() {
var walletCheck = $('#wallet').val();
if (reg.test(walletCheck)) {
alert("Valid address");
} else {
alert("Invalid address");
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" id="wallet" maxlength="34" pattern="^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$" placeholder="Your Bitcoin wallet's address" />
<br>
<br>
<button id="button1">Click for a quote!</button>
So you are missing a few things syntactically in your javascript code.
Your if condition needs to go in a bracket.
Use '==' or '===' for comparing the condition in if statement
In the last line, correct ')}' to be ')}'.
var walletCheck = $('#wallet').val();
var reg = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
$('#button1').click(function() {
if ((reg.test(walletCheck)) === false) {
alert("Inalid Address");
} else {
alert("Valid Address");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="form" id="wallet"
maxlength="34"
pattern="^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
placeholder="Your Bitcoin wallet's address"></input><br><br>
<button id="button1">Click for a quote!</button>
Check this plunk for a working version of your code.

How to trigger function on false?

I have an input form that I want to validate email adresses (or just an # sign). But I only want validation when it's wrong, so remove everything from before the else statement in the jquery snippet?
EDIT
When the user input is wrong, in this case not an emailadress, inform the user.
HTML
<form onsubmit="validate(); return false;">
<p>Enter an email address:</p>
<input id="email">
<button type="submit" id="validate">Validate!</button>
</form>
<br>
<h2 id="result"></h2>
jQuery
function validateEmail(email) {
var re = /#/;
return re.test(email);
}
function validate(){
$("#result").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#result").text(email + " is valid :)");
$("#result").css("color", "green");
} else {
$("#result").text(email + "is not valid :(");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
You can use not operator ! to reverse the condition like this:
function validate(){
$("#result").text("");
var email = $("#email").val();
if (!validateEmail(email)) { //email is invalid?
$("#result").text(email + "is not valid :(");
$("#result").css("color", "red");
//call a function to trigger
return false;
}
}

Compare two emails in two text fields using Javascript

I have a form which lets the user to enter the email address twice. i need to validate that the email is like the regex and that the two emails match.
Something is wrong with my code. Please note that i am restricted to use javascript only. Thanks,
this is my javascript
function checkEmail(theForm) {
var re = /^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"+"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$/i;
if (theForm.EMAIL_1.value != re) {
alert('invalid email address');
return false;
} else if (theForm.EMAIL_1.value != theForm.EMAIL_2.value) {
alert('Those emails don\'t match!');
return false;
} else {
return true;
}
}
Your issue your not actually performing a regex. Your just comparing a regex string to an email.
if(theForm.EMAIL_1.value != re) /// <--- wrong.
{
alert('invalid email address');
return false;
}
On errors, use Event.preventDefault(); to prevent the form submit
Check for email validity only on the first input value
Than check to string equality on both input fields
function checkEmail (event) {
const e1 = this.EMAIL_1.value;
const e2 = this.EMAIL_2.value;
//Email Regex from //stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test( e1 );
const isMatch = e1 === e2;
if( !isEmail ){
event.preventDefault();
alert('Invalid email address');
}
else if ( !isMatch ){
event.preventDefault();
alert("Those emails don't match!");
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
Since you might have more forms where an email is required (Contact form, Login form, Newsletter form, etc etc...) for more modularity you could create a reusable function for validation and than a specific form submit handler separately:
/**
* #param {string} a Email address 1
* #param {string} b Email address 2
* #return {string} Error message
*/
function invalidEmails (a, b) {
a = a.trim();
b = b.trim();
if (!a || !b) return "Missing email";
// Email Regex from stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test(a);
const isMatch = a === b;
if (!isEmail) return "Invalid email";
else if (!isMatch) return "Emails do not match";
}
// Handle your form here
function formSubmitHandler (evt) {
const is_emails_invalid = invalidEmails(this.EMAIL_1.value, this.EMAIL_2.value);
if (is_emails_invalid) {
evt.preventDefault(); // Prevent form submit
alert(is_emails_invalid); // Show error message
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
You cant compare the first value with a regex. You have to use a regexp object. For more information read at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Try this below function to validate your email.
And after the validation, compare the 2nd email.
Please note that regex test method is used in the validateEmail method.
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
The below should work perfectly!
function validateForm(theForm) {
if (theForm.Email_1.value != theForm.Email_2.value)
{
alert('Emails don\'t match!');
return false;
} else {
return true;
}
}

How can I validate a text box, which should only allow characters A-Z & a-z, not integers nor special characters

How to validate a text box in html, where user will enter his first name, and input do not accept integers & Special Characters?
<input name="txtfname" type="text" maxlength="30" required />
Try this javascript code for validation
function Validate()
{
var val = document.getElementById('your_input_control_id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
return true;
}
You will want to check the username field on both the client and server side.
Javascript:
var username = document.getElementsByName("txtfname")[0].value;
if (username .match(/^[A-Za-z]+$/)) {
// Valid
} else {
// Invalid
}
PHP:
$username = $_POST['txtfname'];
if (preg_match("/^[A-Za-z]+$/", $username ) {
// Valid
} else {
// Invalid
}
In Javascript
var uname = document.form.username;
function validate(){
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
return false;
}
}
In Html
<form method="post" action="#" onSubmit="return validate();" name="form">
<input type="text" name="username" class="username"/>
<input type="submit" value="submit">
</form>
This is the proper RegEx.
The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. This RegEx will also work for names like André.
^[\p{L} .'-]+$
var username = document.getElementsById("fname").value;
if (username .match(/^[\p{L} \.'\-]+$/)) {
// Valid username
} else {
// Invalid username
}

Email validator

Having troubles with my email validation code. I keep on getting the error that my function is not defined. i have made a javascript file for the java code and then i used the onchange in my html to trigger the function.
<input type="text" id="email" name="email" onchange="check();" />
function check() {
email = document.getElementById("email").value;
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value))
{
document.getElementById("email").style.border = "3px solid green";
return true;
}
else
{
document.getElementById("email").style.border = "3px solid red";
return false;
}
}
Put your javascript in <script> tags.
Also rename your variable name email since your textbox is using it already.
<input type="text" id="email" name="email" onchange="check();" />
<script type="text/javascript">
function check() {
var email_x = document.getElementById("email").value;
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
document.getElementById("email").style.border = "3px solid green";
return true;
} else {
document.getElementById("email").style.border = "3px solid red";
return false;
}
}
</script>
Email validation is not always as simple as your regular expression. Have you looked at:
Validate email address in JavaScript?
A better option would be to use Verimail.js. It's a simple script that takes care of it for you. With Verimail.js you could just do:
var email = "cool#fabeook.cmo";
var verimail = new Comfirm.AlphaMail.Verimail();
verimail.verify(email, function(status, message, suggestion){
if(status < 0){
// Incorrect syntax!
}else{
// Syntax looks great!
}
});
The above example will hit the line 'Incorrect syntax!' because of the invalid TLD 'cmo'. Besides this, it will also give a suggestion that you can return to your user, in this case, the suggestion variable will contain 'cool#facebook.com' since 'fabeook.cmo' looks a lot like 'facebook.com'.
Hope this helps!
Here is the code for html input field and button field
<input input type="text" name="txtEmailId" id="txtEmailId" />
<input type="submit" class="button" value="Suscribe" name="Suscribe"
onclick="javascript:ShowAlert()" />
Now add the below function to the header of your page
<script type="text/javascript">
function ShowAlert() {
var email = document.getElementById('txtEmailId');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
else {
alert("Thanks for your intrest in us, Now you
will be able to receive monthly updates from us.");
document.getElementById('txtEmailId').value = "";
}
}
</script>
Here you can find the article on this Email Validation in JavaScript
If you are specific about the domains , you may use this code for email validation so as to prevent anonymous email domains.
(^([a-zA-Z]{1,20}[-_.]{0,1}[a-zA-Z0-9]{1,20})(\#gmail\.com|\#yahoo\.com|\#hotmail\.com)$)
You may add additional domains too.

Categories