How to validate login and Registration form in C#. Verify valid UserName, Password, Email, and Phone Number in C#. In this C#, Programming example let’s see some easy steps to validate the login and registration forms.
Data validation is very important to secure the application. So design the front-end element that will allow only valid data or data into a specific format. Let’s take an example of login and registration form in C# and validate all the inputs fields of the login and registration form.
What is form validation?
Form validation is a “technical process where a web form checks if the information provided by a user is correct or not.” The form will either alert the user that they messed up and need to fix something to proceed, or the form will be validated and the user will be able to continue with their registration process.
There are many types of validation in C# that we can use to validate the field of any registration form or any other form which takes inputs or values from the user. They are given below.
- Textbox Validation in C#
- UserName Validation in C#
- Password Validation in C#
- Email Validation in C#
- Phone number Validation in C#
- Textbox validation in C#
The validation of TextBox will be performed using the Validating event handler and the error message will be displayed using the ErrorProvider control in Windows Application (WinForms) using C#.
Textbox Validation in C#
Step 1: Create a Windows form application. In this, we place one text box, one label the text of the label is “Name:-“, and two buttons with the name Enter and Cancel.
Step 2: Select the Text box and go to its properties.
Step 3: Choose the “ErrorProvider” form toolbox.
In properties choose “Events” and under focus double click on “validating”.
Now we have the text box validation method.
private void textBoxName_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrWhiteSpace(textBoxName.Text)) { e.Cancel = true; textBoxName.Focus(); errorProviderApp.SetError(textBoxName, "Name is required!"); } else { e.Cancel = false; errorProviderApp.SetError(textBoxName, ""); } }
Step 4: Now validation should be triggered on entering the keypress. Add the following code to Enter key click method:
private void buttonEnter_Click(object sender, EventArgs e) { if (ValidateChildren(ValidationConstraints.Enabled)) { MessageBox.Show(textBoxName.Text, "Demo App - Message!"); } }
Also, make sure that Enter button’s “CauseValidation” property should be set to “true”.
Now our window form is ready with validation. When we left the textbox empty it will show the error icon when we click on the icon the error message will show as below.
In this way, we learn how to validate textbox using C#.
UserName Validation in C#
We want to set the rules when the user chooses their username. In most cases, a pattern with letters and numbers is used. We also want to set the length of the username so it does not look ugly. We use the following regular expression to validate a username.
[a-zA-Z] => first character must be a letter
[a-zA-Z0-9] => it can contain letter and number
{5,11} => the length is between 6 to 12
public static bool IsUsername(string username) { string pattern; // start with a letter, allow letter or number, length between 6 to 12. pattern = @"^[a-zA-Z][a-zA-Z0-9]{5,11}$"; Regex regex = new Regex(pattern); return regex.IsMatch(username); }
Password Validation in C#
For the validity of a password, we need to recall the concept when we are creating a password for signup in a website.
While creating a password, we may also have seen the validation requirements on a website like a password should be strong and have −
- Min 6 char and max 14 char
- One upper case
- One special char
- One lower case
- No white space
Let us see how to check the conditions one by one.
Min 8 char and max 14 char:
if (passwd.Length < 6 || passwd.Length > 14) return false;
One upper case:
if (!passwd.Any(char.IsUpper)) return false;
At least one lower case:
if (!passwd.Any(char.IsLower)) return false;
No white space:
if (passwd.Contains(" ")) return false;
Check for one special character:
string specialCh = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\""; char[] specialCh = specialCh.ToCharArray(); foreach (char ch in specialChArray) { if (passwd.Contains(ch)) return true; }
Email Validation in C#
let’s see how to validate the email address in C#. We can use the C# Regex class and regular expressions to validate an email in C#. The following Regex is an example to validate an email address in C#. The example defines an IsValidEmail method, which returns true if the string contains a valid email address and false if it doesn’t but takes no other action.
To verify that the email address is valid, the IsValidEmail method calls the Regex.replace(String, String, MatchEvaluator) method with the (@)(.+)$ regular expression pattern to separate the domain name from the email address. The third parameter is a MatchEvaluator delegate that represents the method that processes and replaces the matched text. The regular expression pattern is interpreted as follows.
using System; using System.Globalization; using System.Text.RegularExpressions; namespace RegexExamples { class RegexUtilities { public static bool IsValidEmail(string email) { if (string.IsNullOrWhiteSpace(email)) return false; try { // Normalise the domain email = Regex.Replace(email, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200)); // Examines the domain part of the email and normalises it. string DomainMapper(Match match) { // Use IdnMapping class to convert Unicode domain names. var idn = new IdnMapping(); // Pull out and process domain name (throws ArgumentException on invalid) string domainName = idn.GetAscii(match.Groups[2].Value); return match.Groups[1].Value + domainName; } } catch (RegexMatchTimeoutException e) { return false; } catch (ArgumentException e) { return false; } try { return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)); } catch (RegexMatchTimeoutException) { return false; } } } }
Phone number Validation in C#
When asking a user to enter a mobile number, we usually validate if a number has 10 digits or not. If not, we ask the user to enter the full mobile number. In this case, the following code should be written as the regular expression on the textbox which validates the number.
System.Text.RegularExpressions.Regex expr; public bool phone(string no) { expr = new Regex(@"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$"); if (expr.IsMatch(no)) { return true; } else return false; }