Tuesday, June 28, 2016

Validation with Regular expression


Validation code behind using Regularexpression class Regex 
//Calling method
value  = yourvalue(string,int or Email)
bool bCheck = NumberValidation(value);  - Calling method
bCheck  -- Return Value
if (bCheck == false)
{
 //not matching
}
Else
{
 //matching

}

1. Number validation  - Only numbers (1,2,3,...)

private bool NumberValidation(string value)
{
Regex regex = new Regex("^[0-9]*$");
if (regex.IsMatch(value))
{
countCheck = 0;
return true;
}
else
{
if (countCheck == 1 && tPalceholdervalue != "")
{
countCheck = 0;
MessageBox.Show("Only numbers may be entered here", "Restriction");
return false;
}
return false;
}
}

2. Alphanumeric  (combination numbers and alphabets )

private bool AlphNumeric(string value)
{
Regex regex = new Regex(@"[a-zA-Z0-9/'.]{1,40}");
if (regex.IsMatch(value))
{
countCheck = 0;
return true;
}
else
{
if (countCheck == 1 && tPalceholdervalue != "")
{
countCheck = 0;
MessageBox.Show("No Special Characters", "Restriction");
return false;
}
return false;
}
}

3.Email Validation

private bool EmailCheck(string value)
{

Regex regex = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
if (regex.IsMatch(value))
{
countCheck = 0;
return true;
}
else
{
if (countCheck == 0 && tPalceholdervalue != "")
{
countCheck = 1;
MessageBox.Show("Ex: yourname@email.com", "Restriction");
return false;
}
return false;
}
}

4. Name Validation
private bool NameValidation(string value)
{
value = value.TrimEnd();
Regex regex = new Regex(@"^[0-9a-zA-Z ]+$");
if (regex.IsMatch(value))
{
countCheck = 0;
return true;
}
else
{
if (countCheck == 1 && tPalceholdervalue != "")
{
countCheck = 0;
MessageBox.Show("Special Characters are not allowed", "Restriction");
return false;
}
return false;
}
}

5. Date Validation 
private bool DateValidation(string value)
{
Regex regex = new Regex(@"\d{1,2}\/\d{1,2}/\d{4}");
if (regex.IsMatch(value))
{
countCheck = 0;
return true;
}
else
{
if (countCheck == 1 && tPalceholdervalue != "")
{
countCheck = 0;
MessageBox.Show("Date format : MM/DD/YYYY", "Restriction");
return false;
}
return false;
}
}

6. Boolean Validation

private bool BooleanValidation(string value)
{
if (value.ToUpper() == "YES" || value.ToUpper() == "NO")
{
countCheck = 0;
return true;
}
else
{
if (countCheck == 1 && tPalceholdervalue != "")
{
countCheck = 0;
MessageBox.Show("Ex: Yes or No", "Restriction");
return false;
}
return false;
}
}




No comments:

Post a Comment