04 March 2013

VB.NET: Email Validation (Multipe Email)

Lajutan dari: http://rani-irsan.blogspot.com/2013/02/vbnet-email-validation.html
Kali ini jika textbox mengizinkan menginput lebih dari 1 email dengan pemisah titik koma.
Sama seperti sebelumnya, atur layout sebagai berikut:


Code import:
Imports System.Text.RegularExpressions

Function untuk validasi adalah sebagai berikut.
Private Shared Function MultipleEmailValid(ByVal EmailAddress As _
        String) As String
 Dim IsMatch As Boolean
 Dim sEmail As String
 Dim Email As String
 Dim isValid As String = ""
 Dim regex As Regex = New Regex("([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})", RegexOptions.IgnoreCase _
                          Or RegexOptions.CultureInvariant _
                          Or RegexOptions.IgnorePatternWhitespace _
                          Or RegexOptions.Compiled _
                          )

 If EmailAddress.Trim.Length = 0 Then
    Return "Email Address must be filled."            
 Else
    sEmail = Replace(Replace(EmailAddress, "; ", ";"), " ;", ";")
    If sEmail.Substring(sEmail.Length - 1, 1) = ";" Then _
       sEmail = sEmail.Remove(sEmail.Length - 1, 1)

    Dim Emails As String() = sEmail.Split(New Char() {";"c})

    For Each Email In Emails
        IsMatch = regex.IsMatch(Email) And _
                  Email.Equals(regex.Match(Email).ToString)
        If IsMatch Then
           isValid = ""
        Else
           isValid = "Invalid email address format." & vbCrLf & _
                     "Separate multiple email by semicolon(;)."
           Exit For
        End If
    Next
    Return isValid
 End If
End Function


Kemudian panggil function tersebut pada event Form2_Load dan TextBox1_TextChanged
Private Sub Form2_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
    Me.ErrorProvider1.SetError(Me.TextBox1, _
    MultipleEmailValid(Me.TextBox1.Text))
End Sub

Private Sub TextBox1_TextChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Me.ErrorProvider1.SetError(Me.TextBox1, _
    MultipleEmailValid(Me.TextBox1.Text))
End Sub


Run debug dan coba masukan beberapa karakter pada textbox.






Click here if you like this article.


6 comments:

Anonymous said...

numpang tanya mbak,,,
gimana caranya menampilkan hasil select count(*) from ... where ...=... ke komponen text1.text ato ke variabel lah. terima kasih banyak

rani irsan said...

udah dibales ya comment nya di http://rani-irsan.blogspot.com/2012/07/8-filter-data-dengan-keyword.html

Akhirudin Fahmi said...

Kereeen... :)

rani irsan said...

@mas fahmi: makasih udah mampir :D

agungnovian said...

Keren tante... :-bd

rani irsan said...

weiizzz... ada bung rompal nyasar kemari hehe...
makasih mas ado, udah mampir