Validating email addresses using jQuery and regex - regex

I'm not too sure how to do this. I need to validate email addresses using regex with something like this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)
Then I need to run this in a jQuery function like this:
$j("#fld_emailaddress").live('change',function() {
var emailaddress = $j("#fld_emailaddress").val();
// validation here?
if(emailaddress){}
// end validation
$j.ajax({
type: "POST",
url: "../ff-admin/ff-register/ff-user-check.php",
data: "fld_emailaddress="+ emailaddress,
success: function(msg)
{
if(msg == 'OK') {
$j("#fld_username").attr('disabled',false);
$j("#fld_password").attr('disabled',false);
$j("#cmd_register_submit").attr('disabled',false);
$j("#fld_emailaddress").removeClass('object_error'); // if necessary
$j("#fld_emailaddress").addClass("object_ok");
$j('#email_ac').html(' <img src="img/cool.png" align="absmiddle"> <font color="Green"> Your email <strong>'+ emailaddress+'</strong> is OK.</font> ');
} else {
$j("#fld_username").attr('disabled',true);
$j("#fld_password").attr('disabled',true);
$j("#cmd_register_submit").attr('disabled',true);
$j("#fld_emailaddress").removeClass('object_ok'); // if necessary
$j("#fld_emailaddress").addClass("object_error");
$j('#email_ac').html(msg);
}
}
});
});
Where does the validation go and what is the expression?

UPDATES
http://so.lucafilosofi.com/jquery-validate-e-mail-address-regex/
using new regex
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
}
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex email check exists!

This is my solution:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test(emailAddress);
};
Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery

$(document).ready(function() {
$('#emailid').focusout(function(){
$('#emailid').filter(function(){
var email = $('#emailid').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ( !emailReg.test( email ) ) {
alert('Please enter valid email');
} else {
alert('Thank you for your valid email');
}
});
});
});

Lolz this is much better
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/);
return pattern.test(emailAddress);
};

I would recommend that you use the jQuery plugin for Verimail.js.
Why?
IANA TLD validation
Syntax validation (according to RFC 822)
Spelling suggestion for the most common TLDs and email domains
Deny temporary email account domains such as mailinator.com
How?
Include verimail.jquery.js on your site and use the function:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}

Javascript:
var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);
The regex is not allowed for:
abc#gmail..com
abc#gmail.com..
Allowed for:
abc.efg#gmail.com
abc#gmail.com.my
Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/

We can also use regular expression (/^([\w.-]+)#([\w-]+)((.(\w){2,3})+)$/i) to validate email address format is correct or not.
var emailRegex = new RegExp(/^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$/i);
var valid = emailRegex.test(emailAddress);
if (!valid) {
alert("Invalid e-mail address");
return false;
} else
return true;

Try this
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
return pattern.test(emailAddress);
};

you can use this function
var validateEmail = function (email) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if (pattern.test(email)) {
return true;
}
else {
return false;
}
};

Native method:
$("#myform").validate({
// options...
});
$.validator.methods.email = function( value, element ) {
return this.optional( element ) || /[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}
Source: https://jqueryvalidation.org/jQuery.validator.methods/

Related

How to accept comma-separated values in regex pattern Angular

I have a textarea component which accepts these regex patterns:
UserExamble.com,user#,#examble.com,#examble.com
Now i have implemented all above patterns but in textarea, there are supposed to be multiple values seperated by comma, for ex. UserExamble.com,user# or UserExamble.com,user#,#examble.com,#examble.com. This is what i am not able to implement, how can i do this?
Below is my code:
this.userPolicyForm = this.fb.group({
senderRadioBtn: ['Any'],
senderEmailaddress: ['', [Validators.required, Validators.pattern(ValidationPatternConfig.userPolicyEmailAddressPattern)]]
});
and
ValidationPatternConfig.userPolicyEmailAddressPattern=
"^(([^<>()\\[\\]\\\\,;:\\s#\\\"]+(\\.[^<>()\\[\\]\\\\,;:\\s#\\\"]+)*)|(\\\".+\\\")){1,64}#(\\[ipv6:){1}(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\]$"
+"|"+
"^[A-Za-z0-9+.!#$%&'*+/=?^_`{|}~-]{1,64}#\\[(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]$"
+"|"+
"^(([^<>()\\[\\]\\\\,;:\\s#\\\"]+(\\.[^<>()\\[\\]\\\\,;:\\s#\\\"]+)*)|(\\\".+\\\")){1,64}#((\\[[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,}))$"
+"|"+
"^$|^((?!\\.)[\\w-_.]*[^.])(#\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$"
+"|"+
"^([a-zA-Z0-9!#$%&'*+\\/=?^_`\\{|\\}~\\-.]*[^#,\\]\\[<>:;\"()])#$"
+"|"+
"^#(([a-zA-Z0-9]*([-a-zA-Z0-9]*[a-zA-Z0-9]*)\\.)+[a-zA-Z0-9]*([-a-zA-Z0-9]*[a-zA-Z0-9]))$"
I am using reactive forms in angular.
I have seen few stackoverflow answers, but none of them work. I am new to angular and regex, need help.
One thing you can do is to create custom email validator
this.userPolicyForm = this.fb.group({
senderRadioBtn: ['Any'],
senderEmailaddress: ['', [Validators.required, CustomValidators.validateEmail()]]
});
Create a new file for custom-validator.ts
import { AbstractControl, FormControl } from '#angular/forms';
export class CustomValidators {
// validating array of emails
static validateEmail() {
return (control: FormControl) => {
const pattern = new RegExp('^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$', 'i');
let validEmail = true;
if (control.value !== null) {
const emails = control.value.replace(/\s/g, '').split(',').filter((mail: any) => mail.trim());
for (const email of emails) {
if (email && !pattern.test(email)) {
validEmail = false;
}
}
}
return validEmail ? null : { invalid_email: true };
};
}
}
In html, you can add
<div *ngIf="userPolicyForm.controls.senderEmailaddress.hasError('invalid_email')">
Email address must be valid
</div>
From this you can validate in reactive form. Also when you are submitting array of emails, you can trim it to send to API.
You can decide on the patterns which you want to pass in your textbox and then create regex in 2 parts, one containing the pattern with a comma at the end and a greedy + and second part with just the pattern
like this:
let pattern = "(?:[A-z0-9]+#[A-z]+\.[A-z]{2,6})|(?:[A-z0-9]+#[A-z]+)|(?:#[A-z0-9]+\.[A-z]{2,6})|(?:[A-z0-9]\.[A-z]{2,6})"
var regexPattern = '/(?:' + pattern + '[,])+' + pattern + '/'
var regex = new RegExp(regexPattern)
console.log("UserExamble.com,user#some.com,#examble.com,run.com", regex.test("UserExamble.com,user#some.com,#examble.com,run.com"))
you can use this single regex to validate the input.

Flutter Dart: RegEx to extract URLs from a String

This is my string:
window.urlVideo = 'https://node34.vidstreamcdn.com/hls/5d59908aea5aa101a054dec2a1cd3aff/5d59908aea5aa101a054dec2a1cd3aff.playlist.m3u8';
var playerInstance = jwplayer("myVideo");
var countplayer = 1;
var countcheck = 0;
playerInstance.setup({
sources: [{
"file": urlVideo
}],
tracks: [{
file: "https://cache.cdnfile.info/images/13f9ddcaf2d83d846056ec44b0f1366d/12.vtt",
kind: "thumbnails"
}],
image: "https://cache.cdnfile.info/images/13f9ddcaf2d83d846056ec44b0f1366d/12_cover.jpg",
});
function changeLink() {
window.location = "//vidstreaming.io/load.php?id=MTM0OTgz&title=Mairimashita%21+Iruma-kun+Episode+12";
}
window.shouldChangeLink = function () {
window.location = "//vidstreaming.io/load.php?id=MTM0OTgz&title=Mairimashita%21+Iruma-kun+Episode+12";
}
I am using flutter dart.
How can I get window.urlVideo URL link and image URL link and .vtt file link?
Or
How can I get a list of URLs from a String?
I tried finding a way with and without using RegEx but I couldn't.
Any help is apreciated
This may not be the complete regex, but this worked for me for randomly picked links:
void main() {
final text = """My website url: https://blasanka.github.io/
Google search using: www.google.com, social media is facebook.com, http://example.com/method?param=flutter
stackoverflow.com is my greatest website. DartPad share: https://github.com/dart-lang/dart-pad/wiki/Sharing-Guide see this example and edit it here https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00""";
RegExp exp = new RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+');
Iterable<RegExpMatch> matches = exp.allMatches(text);
matches.forEach((match) {
print(text.substring(match.start, match.end));
});
}
Result:
https://blasanka.github.io/
www.google.com
facebook.com
http://example.com/method?param=flutter
stackoverflow.com
https://github.com/dart-lang/dart-pad/wiki/Sharing-Guide
https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00
Play with it here: https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00
Try this,
final urlRegExp = new RegExp(
r"((https?:www\.)|(https?:\/\/)|(www\.))[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9]{1,6}(\/[-a-zA-Z0-9()#:%_\+.~#?&\/=]*)?");
final urlMatches = urlRegExp.allMatches(text);
List<String> urls = urlMatches.map(
(urlMatch) => text.substring(urlMatch.start, urlMatch.end))
.toList();
urls.forEach((x) => print(x));
Getting just the https? and ftp url's that are in quotes is this :
r"([\"'])\s*((?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-zA-Z0-9\u00a1-\uffff]+-?)*[a-zA-Z0-9\u00a1-\uffff]+)(?:\.(?:[a-zA-Z0-9\u00a1-\uffff]+-?)*[a-zA-Z0-9\u00a1-\uffff]+)*(?:\.(?:[a-zA-Z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/(?:(?!\1|\s)[\S\s])*)?)\s*\1"
Where the Url is captured in group 2.
https://regex101.com/r/UPmLBl/1
Much safer to use a library like linkify instead of rolling your own regex.
/// Attempts to extract link from a string.
///
/// If no link is found, then return null.
String extractLink(String input) {
var elements = linkify(input,
options: LinkifyOptions(
humanize: false,
));
for (var e in elements) {
if (e is LinkableElement) {
return e.url;
}
}
return null;
}

How to validate a component path name in ColdFusion / Lucee

this seems like a simple question but I couldn't find the answer. If I have a component path "pathToComponent", how can I validate that it is valid? Right now I am resorting to using try/catch, but surely there is a more elegant way?
boolean function isValidComponent( required string pathToComponent ){
try{
var metaData = getComponentMetaData( arguments.pathToComponent );
return true;
}
catch( any e ){
return false;
}
}
Thanks!
If you want to test if the component path can be used to create a component, use:
boolean function isValidComponent( required string pathToComponent ) {
try {
createObject("component", ARGUMENTS.pathToComponent);
return true;
}
catch(any) {
}
return false;
}
If you want to access the component physically, use:
string function getComponentLocation( required string pathToComponent ) {
var normalizedPath = replaceNoCase(ARGUMENTS.pathToComponent, ".", "/", "ALL");
var resolvedPath = expandPath(normalizedPath);
var fileLocation = (resolvedPath & ".cfc");
return fileLocation;
}

Multiple email validation using ko.observable

I'm new to the durandal application. Currently i was trying to validate the multiple email readed from the text area.
<textarea class="fullWidth" id="AddEmailSeparatedByComma" rows="3"
data-bind="value:emailList"></textarea>
I have readed multiple email seperated by "," and i was storing in
emailList = ko.observable("").extend({
email: { message: "Please enter valid email address", params: true }
});
I have provided validation message as above. Currently it is validating one email only, i don't know how to use customized regex here to validate multiple email which is separated by comma. Any help will be much appreciated.
Add another validation rule:
ko.validation.rules['emaillist'] = {
validator: function (val, validate) {
if (!validate) return true;
if (ko.validation.utils.isEmptyVal(val)) return true;
var emailrule = ko.validation.rules['email'];
var vals = val.split(/\s*,\s*/);
for (var i = 0; i < vals.length; i++) {
if (!emailrule.validator(vals[i], true)) {
return false;
}
}
return true;
},
message: 'Please enter proper comma-separated email addresses'
};
ko.validation.addExtender('emaillist');
Fiddle

Validating Email Address.(domain)

I'm Using EmailValidator for Validation:
<mx:EmailValidator id="Email_Validator"
source="{txtEmail}"
property="text" required="false"/>
And My Code is:
var isValidForm:Boolean=true;
var validatorArr:Array = new Array();
validatorArr.push(Email_Validator);
var validatorErrorArray:Array = Validator.validateAll(validatorArr);
isValidForm = validatorErrorArray.length == 0;
if(isValidForm)
{
//.....
}
It is working fine. But I want domain should be "gmail.com" if some other, validation should return false.. How can I achive this?
I think Regular Expressions are usefull.. But I dont Know to use the same in flex?...
If all you are testing for is "gmail.com", you don't need to use regular expressions at all. A simple
if (txtEmail.text.indexOf ("gmail.com") < 0) doStuff();
// index < 0 => address does not contain search string
would be enough.
Nonetheless, ActionScript 3 has the RegExp class to provide regular expression functionality. See this tutorial.
Use a component
checkout this
public class TextInputEmail extends TextInput
{
private var emailValidator:EmailValidator = new EmailValidator();
private var validator:ValidationResultEvent;
public function TextInputEmail()
{
super();
this.emailValidator.source = this;
this.emailValidator.property = "text";
this.addEventListener("enter", this.validate);
}
private function validate(event:Event):void
{
validator = emailValidator.validate();
if (validator.type == ValidationResultEvent.VALID)
{
this.errorString = "";
} else {
this.errorString = validator.message;
}
}
}
error strings are in build in Package.
I hope this helps you better...:-)