Creating Utility Class for Email ID and Phone Number Validation

Introduction

Instead of using the Regular Expression or using the javascript on every required page, to validate Email id and Phone No., we can use the given below code on the server side by creating a Utility class.

  1. In AppCode Folder create a file named as AppUtility
  2. Write the below mentioned code in the Utility page and access the same from any required page

// Validating Email ID

public bool IsValidEmail(string strIn)

{

    bool isValid;

    // Return true if strIn is in valid e-mail format.

    if (isValid = Regex.IsMatch(strIn,

    @"((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)|(['\&quot;][^\<\>'\&quot;]*['\&quot;]\s*\<\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\>))(,\s*((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)|(['\&quot;][^\<\>'\&quot;]*['\&quot;]\s*\<\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\>)))*"))

    isValid = true;

    return isValid;

}

 

//Validating Phone No

public bool IsValidPhone(string strPhone)

{

    bool isValid;

    // Return true if strIn is in valid e-mail format.

    if (isValid = Regex.IsMatch(strPhone,("^[0-9]")))

    isValid = true;

    return isValid;

}

// Use the above code in any required page.

 AppUtility app = new AppUtility();

if (app.IsValidEmail(txtEmailIdList.Text) || app.IsValidPhone(txtMobileList.Text))

{

    success = true;

}

Ebook Download
View all
Learn
View all