How can I validate something without using regular expressions in C#? - c#

HI how can I validate a string, but without using regular expressions. For example how can validate this: xxx/xxxx where x is a digit? thanks

Something like that:
bool ValidateExpression(string expression)
{
string[] parts = expression.Split("/");
if (
parts.Length != 2
|| parts[0].Length != 3
|| parts[1].Length != 4
) return false;
int parsed;
return Int32.TryParse(parts[0], out parsed) && Int32.TryParse(parts[1], out parsed);
}
To be used later as
bool isValid = ValidateExpression("123/4567");

You can use Char.IsDigit to check if characters are a digit. For your specific case, you could do something like this:
public bool IsMyStringValid(string myString)
{
foreach(var c in myString)
if(!Char.IsDigit() && !c == '/') return false;
return true;
}
This is actually more specific to your case (3 digits, one '/' at index 3, followed by 4 digits):
public bool IsMyStringValid(string myString)
{
if(myString.Length != 8) return false;
for(var i = 0; i <8, i++)
if(!Char.IsDigit(myString[i]) || (i == 3 && myString[i] == '/') return false;
return true;
}

For that specific format you can use:
bool valid =
value.Length == 8 &&
value.Take(3).All(Char.IsDigit) &&
value[3] == '/' &&
value.Skip(4).All(Char.IsDigit);

Try this :
public bool ValidateString(string str)
{
var strArr = str.Split('/');
return strArr[0].All(char.IsDigit) && strArr[1].All(char.IsDigit);
}
hope this help;

I would use the .All to check something like this so no matter what the string is
if there is a non digit in it, it will not pass
public static bool IsMyStringValid(string strValidateString)
{
bool boolIsValid = false;
if (strValidateString.All(Char.IsDigit))
{
boolIsValid = true;
}
return boolIsValid;
}

Related

How to combine multiple IF statements in C#

I have some flawed logic here..my goal is if all of the fields have "" value then return true, otherwise return false. How can I fix this in C# ?
public bool CheckFieldsAreEmpty()
{
Driver.WaitForElementValueNull(smtpHostInputField);
if (smtpHostInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(smtpPortInputField);
if (smtpPortInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(usernameInputField);
if (usernameInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(passwordInputField);
if (passwordInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(senderInputField);
if (senderInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(receiverInputField);
if (receiverInputField.GetAttribute("value") == "")
return true;
else return false;
I believe something like this should work. I couldn't find what class all of those variables belong to, but replace var with the proper class and I think this should work.
logic: Add all variables to a List, use a lambda function to return if all of the list match GetAttribute("value") == ""
// Replace var with class type, or parent
List<var> allFields = new List<var> { smtpHostInputField, smtpPortInputField, sernameInputField, passwordInputField, senderInputField, receiverInputField };
foreach (var field in allFields) { Driver.WaitForElementValueNull(field); }
return allFields.All(t => t.GetAttribute("value") == "");
To illustrate #madreflection’s (correct) suggestion from the comments, consider this code:
public bool CheckFieldsAreEmpty()
{
Driver.WaitForElementValueNull(smtpHostInputField);
if (smtpHostInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(smtpPortInputField);
if (smtpPortInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(usernameInputField);
if (usernameInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(passwordInputField);
if (passwordInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(senderInputField);
if (senderInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(receiverInputField);
if (receiverInputField.GetAttribute("value") != "")
return false;
return true;
}
Of course, as #Daniel-Lord’s answer highlights, you can centralize this repetitive logic using either a loop or a LINQ query.
Another way to solve this would be to extract WaitForElementValueNull call and empty string check to a separate method. Something like that:
private static bool WaitForElementValueNullAndEmpty(InputFieldType inputField)
{
Driver.WaitForElementValueNull(inputField);
return inputField.GetAttribute("value") == "";
}
public bool CheckFieldsAreEmpty()
{
return WaitForElementValueNullAndEmpty(smtpHostInputField) ||
WaitForElementValueNullAndEmpty(smtpPortInputField) ||
WaitForElementValueNullAndEmpty(usernameInputField) ||
WaitForElementValueNullAndEmpty(passwordInputField) ||
WaitForElementValueNullAndEmpty(senderInputField) ||
WaitForElementValueNullAndEmpty(receiverInputField);
}
The code above will match the algorithm that was provided, however if you want to check if ALL the values is empty then || should be replaced with && (As it was noticed by Jeremy Caney)

Ignore accent letters in string comparison in Visual Studio

I am new to Visual Studio and i'm trying to learn some simple tasks.
I have been given a code that compares two strings (last name and first name)
private bool compareNames(String value1, String value2)
{
if (value1 != null && value2 != null && value1.Trim().ToLower(). Equals(value2.Trim().ToLower()))
{
return true;
}
return false;
}
The code above ignores case sensitive, but what i'm trying to do is to also ignore special characters like ăîşéááö.
I've tried to do this task with Normalize() but it doesnt seem to work.
private bool compareNames(String value1, String value2)
{
if (value1 != null && value2 != null && value1.Trim().ToLower(). Equals(value2.Trim().ToLower()))
{
return true;
}
else if (value1 != null && value2 != null && value1.Trim().Normalize().Equals(value2.Trim().Normalize()))
{
return true;
}
return false;
}
Any help is appreciated!
One of the possible answers is to use the RemoveDiacritcs approach.
static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
More info here : How do I remove diacritics (accents) from a string in .NET?

Can't get the correct Bool result in C#

I have a form where I would like to check for validation before processing the form. My form has 2 sections so I want to make sure that at least one item from each section is selected when they press submit button, and if they did then go to Dashboard.aspx. Even if I put all the required info when it checks for result1 and result2, I get false. Result1 and Result2 won't get the correct value. Even if the values are True again it passes false.
Here is my code:
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
bool result1 = false;
bool result2 = false;
CheckWireFromValidation(result1);
CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation (bool result1)
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
result1 = true;
}
else
{
result1 = false;
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
}
return result1;
}
public bool CheckWireToValidation(bool result2)
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
result2 = true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
}
return result2;
}
You're not using the results of CheckWireToValidation. You're using the false value you allocate initially.
Try this
bool result1 = false;
bool result2 = false;
if (CheckWireFromValidation(result1) && CheckWireToValidation(result2))
{
Response.Redirect("~/DashBoard.aspx");
}
Edit
The behavior you're expecting is that of the out parameter modifier. But please don't write code that way ...
I edited your code to get rid of .. em .. cruft. This should be more readable.
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
if (CheckWireFromValidation() && CheckWireToValidation())
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation ()
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
return false;
}
}
public bool CheckWireToValidation ()
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
return false;
}
}
Since you are passing Result1 and Result2 in as parameters instead assigning them. The results will never be set.
Here's one correct way of doing this
bool result1 = CheckWireFromValidation(result1);
bool result2 = CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
and also a side note. I think we can safely remove the boolean parameter from the CheckWireFromValidation methods. Since the return value doesn't depends on the input variable.
Hope this helps.

Replace commas in string C#

I have a string like this:
select name,lastname,email from contacts
I want to replace the commas for +"|"+
and get something like this
select name+"|"+lastname+"|"+email from contacts
thats easy with string.Replace(",",+"|"+);
but the problem is when i face a string like this:
select name,lastname,isnull(email,0) from contacts
How i cant detect to avoid the commas inside the isnull()?
with the replace i get a string like this
select name+"|"+lastname+"|"+isnull(email+"|"+0) from contacts
and thats wrong!
thanks .
Try this:
public static string ReplaceTopLevelCommas(string query)
{
var newQuery = new StringBuilder();
var level = 0;
foreach (var c in query)
{
if (c == ',')
{
if (level == 0)
{
newQuery.Append("+\"|\"+");
}
else
{
newQuery.Append(c);
}
}
else
{
if (c == '(')
{
level++;
}
else if (c == ')')
{
level--;
}
newQuery.Append(c);
}
}
return newQuery.ToString();
}
It replaces commas only if they're not inside any parentheses. So it will also work for multiple levels of nesting.
Working example: http://ideone.com/TGPRe2
Simply write your own method:
private static string replace_commas(String str_)
{
StringBuilder str = new System.Text.StringBuilder(str_);
bool replace = true;
for(int i = 0; i != str.Length; ++i)
{
if(str[i] == ',' && replace)
str[i] = '|';
if(str[i] == '(')
{
replace = false;
continue;
}
if(str[i] == ')' && !replace)
replace = true;
}
return str.ToString();
}
You fill in the blanks! :-)

.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

I'm attempting to use Contracts in my .Net 3.5 (C#) project. I found where I had written something like if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) throw new ArgumentException("Required", "s"); at the beginning of methods.
I could keep them there and use legacy contracts. I could change it to Contract.Requires(s!= null && string.IsNullOrEmpty(s.Trim()));. But besides not being very sure about the correctness or performance of the Whitespace part of the condition, those are lame (opinion).
Instead, I tried to encapsulate the condition in a method for use in Contracts. Problem is that I still can't figure out how to describe the Whitespace part declaratively. The static checker finds several issues depending on how I write it.
I'd like to hear comments about the appropriateness of data content checks such as this one for whitespace AS WELL AS a correct definition.
public static class str
{
[Pure]
public static bool IsNullOrWhitespace(string s)
{
Contract.Ensures(s != null || Contract.Result<bool>());
Contract.Ensures((s != null && !Contract.ForAll<char>(s, c => char.IsWhiteSpace(c))) || Contract.Result<bool>());
if (s == null) return true;
for (var i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s, i))
{
Contract.Assume(!Contract.ForAll<char>(s, c => char.IsWhiteSpace(c)));
return false;
}
}
return true;
}
}
This might be sloppy, but my initial experimentation method is here. The Asserts on a, b, and c are failing or are unproven.
static void Test()
{
string a = null;
string b = "";
string c = " ";
string d = "xyz";
string e = " xyz ";
if (!str.IsNullOrWhitespace(a))
{
Contract.Assert(a != null);
a = a.Trim();
}
if (!str.IsNullOrWhitespace(b))
{
Contract.Assert(b != null && b != "");
b = b.Trim();
}
if (!str.IsNullOrWhitespace(c))
{
Contract.Assert(c != null && c != " ");
c = c.Trim();
}
if (!str.IsNullOrWhitespace(d))
{
d = d.Trim();
}
if (!str.IsNullOrWhitespace(e))
{
e = e.Trim();
}
}
Here's the built-in contract from .NET 4:
Contract.Ensures(
(Contract.Result<bool>() && ((str == null) || (str.Length == 0)))
? ((bool) true)
: ((Contract.Result<bool>() || (str == null))
? ((bool) false)
: ((bool) (str.Length > 0)))
, null, "Contract.Result<bool>() && (str == null || str.Length == 0) ||\r\n!Contract.Result<bool>() && str != null && str.Length > 0");
Despite its complexity, you can see that there is no mention of whitespace. I've tried several times, but I can't get something working that will satisfy the static checker.
There appear to be a couple of issues stopping me from writing it, so I've filed some questions on the Code Contracts forum.
My contract was:
Contract.Ensures(Contract.Result<bool>() ==
(s == null || Contract.Exists(s, char.IsWhiteSpace)))

Categories