Regular expression validation - initialization error in Javascript - javascript

I am trying to write a function in Javascript to validate email address. Here is the function.
function validateEmailAddress() {
var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/;
var regexPatternForEmail = new RegExp(patternForEmail, 'i');
// Email address and the Confirm Email address values should match
if ($('#txtEmail').val() != $('#txtConfirmEmail').val()) {
$('#dvErrorMsg').html("Email addresses do not match.");
$('#txtEmail').focus();
return false;
}
else if (!regexPatternForEmail.test($('#txtEmail').val())) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}
else
return true;
}
The problem here is I am getting an error, 'Syntax error in regular expression' during RegExp object instantiation.
I tried debuggin in IE 11 and that's where i found the error.
Could someone please suggest me a solution for this.
Screen shot taken while debugging:

You don't need to create another regex variable using RegExp constructor. Just use only the below.
var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/i;
i at the last called case-insensitive modifier which helps to do a case-insensitive match.
Example:
> var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/i;
> patternForEmail.test('foo#bar.com')
true
> patternForEmail.test('#foo#bar.com')
false

In most of the times this kinds of errors occurs because of browser compatibility , so always we need to use the codes which can be run in all the browsers. I hope the following changes will help you.
var patternForEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
then you can match the expression using
if (patternForEmail.test($('#txtEmail').val())) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}
or else you can use match() function also which will be more flexible for all the browsers.
var email = $('#txtEmail').val();
if (!email.match(/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i)) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}

Related

How to validate text input in React Native

I am trying to validate inputText to make sure it is a correctly formatted email address. However, I'm getting the following issues:
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(emailText) === false) {
alert('Email is Not Correct');
// this.setState({email: emailText});
return false;
} else {
// this.setState({email: emailText});
alert('Email is Correct');
}
Works with some issues the following:
hello#gmail.com // works
hello.world#gmail.com // works
some.thing#gm.ci.co // will not work and is a real email address
Another other issue is that my characters count is limited. How do I remove the limit? I need to be able to have unlimited characters

Javascript method to check for digits within a string (validation of input data)

Im trying to implement a validation for an input field in IBM BPM.
Im not really familiar with java script but I try to get method that returns
ture if a string contains any numbers.
awdadw = valid
awdawd2d = invalid
I tried this method:
function hasNumbers(t)
{
var pattern=new RegExp("^[A-Za-z]+$");
return pattern.test(t); // true if string. Returns false for numbers
}
When I try this function, it says that method / variable RegExp is unknown. Since it is rather basci stuff I hope to get some sources where this topic is explained.
You can use this:
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("inputID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Based on adre3wap this worked for me:
function validate(t){
var re = /^[A-Za-z]+$/;
if(re.test(t))
return false;
else
return true;
}

how to validate either email or mobile in same input field?

I have coded not empty on fields. how do i check that email is valid or either mobile number is valid one that too us phone number.
if(mob_or_email==""){
document.getElementById('busp_email').innerHTML="Mobile/Email required";
$("#busp_email").removeClass('field_validation_error hidden');
$("#busp_email").addClass('field_validation_error');
$("#busi_name").css("color","#f42156");
}
if($('#login_password').val()==""){
document.getElementById('logp_pwd').innerHTML="Password required";
$("#logp_pwd").removeClass('field_validation_error hidden');
$("#logp_pwd").addClass('field_validation_error');
$("#log_pwd").css("color","#f42156");
}
If I understand your request correctly, you may have an e-mail or a phone number in the same field?
You will need regular expressions for this (If my suggestions are not satisfying, search trough the internet, there are many samples for specific cases)
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
function validatePhone(phone) {
var re = /^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/;
return re.test(phone);
}
With these functions you can validate e-mail and us phone numbers.
just use
if (validateEmail(mob_or_email) or validatePhone(mob_or_email)) {
//is either a valid email or (us) phone number
}

How to check specific email validation in phonegap android

I had created an registration form in which i had created and email i had provided validation to all the filed but I'm confused how to give validation to email field because i want that email should be either gmail.com or yahoomail.com if some one enters any other email even yahoomail.co.in it should give error message.
here is the code i which checking that its having # and . in the email or not
var atdrate=email.indexOf("#");
var dot1=email.indexOf(".");
else if(atdrate<1 || dot1<1)
{
alert("Enter valid Email");
if(gml<atdrate+1)
alert("Enter a vaild mail id");
else if(yml<atdrate+1)
alert("Enter a valid email id");
}
Using Regular Expressions is probably the best way. Here's an example (live demo):
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);
}
But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.
*answer from https://stackoverflow.com/a/46181/1521984
Update: Then use the JavaScript split() function to split the mail address after the '#' and check the value versus your strings.
var mail = yourMailAdress.split("#");
if (mail[1] == "gmail.com" || mail[1] == "yahoomail.com") {
// OKAY
} else {
// false
}

Javascript isEmailValid

Using JSLint I can't get my isEmailValid working, what is wrong with the code? I get different error messages like local was not defined before it was used or # invalid character or ^ is not enclosed but for the email it could have the symbol "^"?
function isEmailValid(email) {
"use strict";
var e = (email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
Validate email addresses client-side with this regular expression:
/.#./
And then do the real validation server-side by sending an email to that address.
Working email addresses can and do exist that do not conform to any spec. There's no sense restricting users because their valid email address looks wrong, while at the same time allowing users to enter email addresses that look right, but are fake (eg, iwontgiveyoumyrealemailaddress#noreply.com looks real to a computer, but probably isn't).
Required reading
I would suggest using regex:
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);
}
See also: Validate email address in JavaScript?
You're getting the error about local because you're not actually declaring it as a local variable within the function.
var statements don't contain or use parenthesis. So, using them anyways as:
var e = (email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
Is equivalent to:
local = /[^\w.!#$%&*+-\/=?^_{|}~]/;
domain = /[^\w.-]/;
var e = (email.split("#"), local, domain);
e will then be set to the result of the parenthesis being evaluated, which simply contain operands for comma operators. So, the last line is equivalent to:
email.split("#");
local;
var e = domain;
And, as that doesn't seem to be what you wanted, you probably don't want the parenthesis:
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/;

Categories