I've tried implementing a rather simple email validation function that seems return a false match even though the input is a valid email. I have searched for any issues with the existing regex but it seems to be correct.
Even though the match returns a false value the program is stepping to the next validation level (which it shouldn't).
Here is the email validation function.
Function EmailAddressChecker(ByVal emailAddress As String) As Boolean
Dim regExPattern As String = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$"
Dim emailAddressMatch As Match = Regex.Match(emailAddress, regExPattern)
If emailAddressMatch.Success Then
Return True
Else
Return False
End If
End Function
And for the form validation that calls upon the email validation function.
If (String.IsNullOrEmpty(EmailTextBox.Text) OrElse EmailAddressChecker(EmailTextBox.ToString)) Then
MessageBox.Show("Please enter a valid email addresss")
Return False
End If
The call for all of this happens on an click event which triggers a cascading serious of If statements checking to see if all the fields are set.
Skipping a large chunk of code the click event asks if "AreFieldsSet <> True". Inside of the "AreFieldsSet" function contains all the validation for multiple inputs; one of which is the email validation if statement.
Are the emails in UpperCase? If they aren't, they won't match.
If you want to modify the Regex so that it is Case insensitive, use this:
"^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
To validate the email address you need to use the IsMatch function of the Regex object, it evaluate if the entry email address is valid.
Function EmailAddressChecker(ByVal emailAddress As String) As Boolean
Dim r As System.Text.RegularExpressions.Regex = Nothing
Dim regExPattern As String = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$"
If r.IsMatch(emailAddress ,regExPattern ) Then
Return True
Else
Return False
End If
End Function
You can try this code for your form validation If (String.IsNullOrEmpty(EmailTextBox.Text) OrElse EmailAddressChecker(EmailTextBox.ToString)<>true) Then
MessageBox.Show("Please enter a valid email addresss")
Return False
End If
Public Shared Function ValidEmailAddress(ByVal emailAddress As String, ByRef errorMessage As String) As Boolean
If emailAddress.IndexOf("#") > -1 Then
If (emailAddress.IndexOf(".", emailAddress.IndexOf("#")) > emailAddress.IndexOf("#")) AndAlso emailAddress.Split(".").Length > 0 AndAlso emailAddress.Split(".")(1) <> "" Then
errorMessage = ""
Return True
End If
End If
Return False
End Function
Related
I have a variable like this:
const domain_issuer = "some array of domains"
const url_setter = domain_issuer !== null ? domain_issuer[0] : '';
the domain_issuer is grabbing the domains from a config file that has arrays of different domains and it uses a regex to match a specific domain. So the url_setter checks to see if domain_issuer is null or not null and if it is null it assigns it to an empty string, if not, the first match gets assigned to url_setter
My branch coverage says the '' (empty string) is not covered. I tried different things to reach that statement but nothing seems to work.
How can I cover this?
I need to send a custom email message to every User of a list ( List < User > ) I have. (I'm using C# .NET)
What I would need to do is to replace all the expressions (that start with "[?&=" have "variableName" in the middle and then ends with "]") with the actual User property value.
So for example if I have a text like this:
"Hello, [?&=Name]. A gift will be sent to [?&=Address], [?&=Zipcode], [?&=Country].
If [?&=Email] is not your email address, please contact us."
I would like to get this for the user:
"Hello, Mary. A gift will be sent to Boulevard Spain 918, 11300, Uruguay.
If marytech#gmail.com is not your email address, please contact us."
Is there a practical and clean way to do this with Regex?
This is a good place to apply regex.
The regular expression you want looks like this /\[\?&=(\w*)\]/ example
You will need to do a replace on the input string using a method that allows you to use a custom function for replacement values. Then inside that function use the first capture value as the Key so to say and pull the correct corresponding value.
Since you did not specify what language you are using I will be nice and give you an example in C# and JS that I made for my own projects just recently.
Pseudo-Code
Loop through matches
Key is in first capture group
Check if replacements dict/obj/db/... has value for the Key
if Yes, return Value
else return ""
C#
email = Regex.Replace(email, #"\[\?&=(\w*)\]",
match => //match contains a Key & Replacements dict has value for that key
match?.Groups[1].Value != null
&& replacements.ContainsKey(match.Groups[1].Value)
? replacements[match.Groups[1].Value]
: "");
JS
var content = text.replace(/\[\?&=(\w*)\]/g,
function (match, p1) {
return replacements[p1] || "";
});
I need a macro in Outlook that extract all the email address in the outlook message then post it in excel.
The following code only extracts the very 1st email address it finds in the body.
My desired output should be:
adam.peters#sample.com
adam.dryburgh#sample.com
amy.norton#sample.com
My sample email is:
Delivery has failed to these recipients or groups:
adam.peters#sample.com The e-mail address you entered couldn't be
found. Please check the recipient's e-mail address and try to resend
the message. If the problem continues, please contact your helpdesk.
adam.dryburgh#sample.com The e-mail address you entered couldn't be
found. Please check the recipient's e-mail address and try to resend
the message. If the problem continues, please contact your helpdesk.
amy.norton#sample.com The e-mail address you entered couldn't be
found. Please check the recipient's e-mail address and try to resend
the message. If the problem continues, please contact your helpdesk.
The following organization rejected your message:
mx2.dlapiper.iphmx.com.
code:
Sub Extract_Invalid_To_Excel()
Dim olApp As Outlook.Application
Dim olExp As Outlook.Explorer
Dim olFolder As Outlook.MAPIFolder
Dim obj As Object
Dim stremBody As String
Dim stremSubject As String
Dim i As Long
Dim x As Long
Dim count As Long
Dim RegEx As Object
Set RegEx = CreateObject("VBScript.RegExp")
Dim xlApp As Object 'Excel.Application
Dim xlwkbk As Object 'Excel.Workbook
Dim xlwksht As Object 'Excel.Worksheet
Dim xlRng As Object 'Excel.Range
Set olApp = Outlook.Application
Set olExp = olApp.ActiveExplorer
Set olFolder = olExp.CurrentFolder
'Open Excel
Set xlApp = GetExcelApp
xlApp.Visible = True
If xlApp Is Nothing Then GoTo ExitProc
Set xlwkbk = xlApp.workbooks.Add
Set xlwksht = xlwkbk.Sheets(1)
Set xlRng = xlwksht.Range("A1")
xlRng.Value = "Bounced email addresses"
'Set count of email objects
count = olFolder.Items.count
'counter for excel sheet
i = 0
'counter for emails
x = 1
For Each obj In olFolder.Items
xlApp.StatusBar = x & " of " & count & " emails completed"
stremBody = obj.Body
stremSubject = obj.Subject
'Check for keywords in email before extracting address
If checkEmail(stremBody) = True Then
'MsgBox ("finding email: " & stremBody)
RegEx.Pattern = "\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b"
RegEx.IgnoreCase = True
RegEx.MultiLine = True
Set olMatches = RegEx.Execute(stremBody)
For Each match In olMatches
xlwksht.cells(i + 2, 1).Value = match
i = i + 1
Next match
'TODO move or mark the email that had the address extracted
Else
'To view the items that aren't being parsed uncomment the following line
'MsgBox (stremBody)
End If
x = x + 1
Next obj
xlApp.ScreenUpdating = True
MsgBox ("Invalid Email addresses are done being extracted")
ExitProc:
Set xlRng = Nothing
Set xlwksht = Nothing
Set xlwkbk = Nothing
Set xlApp = Nothing
Set emItm = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Sub
Function GetExcelApp() As Object
' always create new instance
On Error Resume Next
Set GetExcelApp = CreateObject("Excel.Application")
On Error GoTo 0
End Function
untested
replace
RegEx.Pattern = "\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b"
RegEx.IgnoreCase = True
RegEx.MultiLine = True
with
RegEx.Pattern = "\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b"
RegEx.IgnoreCase = True
RegEx.MultiLine = True
RegEx.Global = True
I have noticed the following line of code:
Set olApp = Outlook.Application
If you run the code in Outlook, you need to use the Application property to get an instance of the Application class. Or you need to use the New operator to create a new instance, for example:
Set ol = New Outlook.Application
or
Set objOL = CreateObject("Outlook.Application")
See How to automate Outlook from another program for more information.
You may also consider using the Word object model for working with item bodies. The WordEditor property of the Inspector class returns an instance of the Document class which represents the message body. See Chapter 17: Working with Item Bodies for more information.
How do I use vbscript to find two texts that match within a singe line? For example:
This UserName is Logged on already.
How do I search for "UserName" and "Logged on"?
Regular expressions are probably overkill in this case. I'd suggest using InStr() for this kind of check:
s = "This UserName is Logged on already."
If InStr(s, "UserName") > 0 And InStr(s, "Logged on") > 0 Then
'...
End If
You can wrap InStr() in a helper function if you want to make the check a bit better readable:
s = "This UserName is Logged on already."
If Contains(s, "UserName") And Contains(s, "Logged on") Then
'...
End If
Function Contains(str1, str2)
Contains = False
If InStr(str1, str2) > 0 Then Contains = True
End Function
I am using the following REGEX
VALID_WEBSITE_REGEX = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?$/ix
to validate a website entry with this rule:
validates :website, length: { maximum: 150 }, format: { with: VALID_WEBSITE_REGEX }
(The 150 is arbitrary).
However, when I save / update the form I get a validation error "website is invalid". How do I ensure that the 'format' section of the validation rule is processed only if there is content to process?
You can use allow_blank option for validation
:allow_blank => true
This option will let validation pass if the attribute’s value is blank?, like nil or an empty string for example.
read more:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#allow_blank
Enclose the entire thing with the ? operator, e.g.
VALID_WEBSITE_REGEX = /^((http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?)?$/ix
If you want to allow whitespace too, then add \s* on each end, e.g.
VALID_WEBSITE_REGEX = /^\s*((http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?)?\s*$/ix