Adding String Length Validation - c#

I am adding validation to my text string. It allows string and integer values, which is correct, but I want to require my text to be greater than 4 characters long. I've added the text.Length > 4 but this does not add any validation when entering a 2 character string. Any suggestions?
public bool IsStringInvalid(string text)
{
if (String.IsNullOrEmpty(text))
{
if (text != null && !Regex.IsMatch(text, textCodeFormat) && text.Length > 4)
{
return true;
}
}
return false;
}

Your method is called IsStringLengthInvalid, which implies that it should be returning true for invalid strings. Right now, it appears you're trying to return true only for valid strings.
Something like this should work:
public bool IsStringInvalid(string text)
{
return string.IsNullOrEmpty(text) ||
text.Length <= 4 ||
!Regex.IsMatch(text, textCodeFormat);
}

You are checking for not null condition nested inside the null condition which is logically wrong. You should do something like this.
public bool IsStringInvalid(string text)
{
if (text != null && text.Length > 4 && !Regex.IsMatch(text, textCodeFormat))
{
return true;
}
return false;
}

You have your length validation if statement nested inside your other if. If text has any data if will never reach the nested if as it will fail the first since IsNullOrEmpty will return false.
I would do something like
if (String.IsNullOrEmpty(text) || !Regex.IsMatch(text, textCodeFormat) || text.Length < 4)
{
return true;
}
return false;

Related

How to handle the integer textbox with value 0

I have 3 textbox
1,Age(year),
2,Age(month),
3,Age(Day))
By Default all 3 texbox value is 0(integer) which means the object assigned to each control is holding the value 0.
ibusbus.icdobus.user_month =0
ibusbus.icdobus.user_year=0
ibusbus.icdobus.user_Day=0
Now I need to validation if the user is make a empty of those textboxes.
So what I did is
public bool IsUserAgeYearisNull()
{
return (ibusbus.icdobus.user_year <= 0);
}
public bool IsUserAgeMonthisNull()
{
return (ibusbus.icdobus.user_month <= 0);
}
public bool IsUserAgeDayisNull()
{
return (ibusbus.icdobus.user_day <= 0);
}
So If user is make empty it is throwing a message.Here there is no issues
But in case User is enter year as 12 and enter 0 for both month and age.It is showing erro for month and Day that user need to enter the value.Here the user can enter 0 but it should not throw error.
Need to check all condition in all functions.
public bool IsUserAgeYearisNull()
{
if (ibusCalcWiz.icdoCalcWiz.user_age_month == 0 && ibusCalcWiz.icdoCalcWiz.user_age_day == 0)
return (ibusCalcWiz.icdoCalcWiz.user_age_year <= 0);
else
return true;
}
public bool IsUserAgeMonthisNull()
{
if (ibusCalcWiz.icdoCalcWiz.user_age_year == 0 && ibusCalcWiz.icdoCalcWiz.user_age_day == 0)
return (ibusCalcWiz.icdoCalcWiz.user_age_month <= 0);
else
return true
}
public bool IsUserAgeDayisNull()
{
if (ibusCalcWiz.icdoCalcWiz.user_age_year == 0 && ibusCalcWiz.icdoCalcWiz.user_age_month == 0)
return (ibusCalcWiz.icdoCalcWiz.user_age_day <= 0);
else
return true;
}
you can also create a common function.
public bool isValid()
{
return (busCalcWiz.icdoCalcWiz.user_age_year > 0 ||
ibusCalcWiz.icdoCalcWiz.user_age_month > 0 ||
ibusCalcWiz.icdoCalcWiz.user_age_day > 0);
}
and call from all function. Like :
public bool IsUserAgeDayisNull()
{
return isValid();
}
You can use a RangeValidator for each of TextBoxes.
Using RangeValidator as suggested earlier would be a better idea rather than writing lots of code. it will become hard to maintain the code in long run.

Convert String To Int in LINQ

I have a LINQ query that queries a DataTable. In the DataTable, the field is a string and I need to compare that to an integer, basically:
if ((electrical >= 100 && electrical <= 135) || electrical == 19)
{
// The device passes
}
the problem is, I am trying to do this in LINQ like this:
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where (Int32.Parse(row.Field<String>("electrical")) >= 100 &&
Int32.Parse(row.Field<String>("electrical")) <= 135) &&
Int32.Parse(row.Field<String>("electrical")) != 19 &&
row.Field<String>("print") == printName
select row;
I keep getting the exception:
Input string was not in a correct format
The main problem occurs when electrical == ""
Unfortunately, the framework doesn't provide a nice clean way to handle parsing scenarios where it fails. Of what's provided, they only throw exceptions or use out parameters, both of which does not work well with linq queries. If any one value you're parsing fails, the entire query fails and you just can't really use out parameters. You need to provide a method to handle the parsing without that does not throw and does not require using out parameters.
You can handle this in many ways. Implement it where upon failure, you return some default sentinel value.
public static int ParseInt32(string str, int defaultValue = 0)
{
int result;
return Int32.TryParse(str, out result) ? result : defaultValue;
}
Or what I would recommend, return a nullable value (null indicating it failed).
public static int? ParseInt32(string str)
{
int result;
return Int32.TryParse(str, out result) ? result : null;
}
This simplifies your query dramatically while still leaving it readable.
public bool GetElectricalStatus(string printName)
{
var query =
from row in singulationOne.Table.AsEnumerable()
where row.Field<string>("print") == printName
// using the nullable implementation
let electrical = ParseInt32(row.Field<string>("electrical"))
where electrical != null
where electrical == 19 || electrical >= 100 && electrical <= 135
select row;
return !query.Any();
}
p.s., your use of the Convert.ToInt32() method is incorrect. It is the same as calling Int32.Parse() and does not return a nullable, it will throw on failure.
I would check if the data in the column does not contain leading/trailing whitespaces - i.e. "15 " rather than "15" and if it does (or might do) trim it before trying to convert:
Int32.Parse(row.Field<String>("electrical").Trim())
BTW: not related to the error but I'd use let statement to introduce a local variable and do the conversion once:
let x = Int32.Parse(row.Field<String>("electrical").Trim())
where x >= 100...
I could not get anything to work, so I re-did the whole method:
public bool GetElectricalStatus(string printName)
{
List<object> eGoodList = new List<object>();
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where row.Field<String>("print") == printName
select row.Field<String>("electrical");
foreach (var eCode in eGoodCountQuery)
{
if (!string.IsNullOrEmpty(eCode.ToString()))
{
int? eCodeInt = Convert.ToInt32(eCode);
if (eCodeInt != null &&
(eCodeInt >= 100 && eCodeInt <= 135) || eCodeInt == 19)
{
eGoodList.Add(eCode);
}
}
}
if (eGoodList.Count() > 0)
{
return false;
}
else
{
return true;
}
}
The main problem occurs when electrical == ""
Why not make a function that does your evaluation, and call it in your Linq query. Put logic in to check the validity of the data contained within (so if you can't parse the data, it should return false)...
The function:
bool IsInRange(string text, int lower, int upper, params int[] diqualifiers)
{
int value = int.MinValue;
if (!int.TryParse(text, out value)) {
return false;
}
if (!(value >= lower && value <= upper)) {
return false;
}
if (disqualifiers != null && disqualifiers.Any(d => d == value)) {
return false;
}
return true;
}
The Linq query...
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where
IsInRange(row.Field<String>("electrical"), 100, 135, 19)
&& row.Field<String>("print") == printName
select row;

Validating a Textbox field for only numeric input.

I have created a form-based program that needs some input validation. I need to make sure the user can only enter numeric values within the distance Textbox.
So far, I've checked that the Textbox has something in it, but if it has a value then it should proceed to validate that the entered value is numeric:
else if (txtEvDistance.Text.Length == 0)
{
MessageBox.Show("Please enter the distance");
}
else if (cboAddEvent.Text //is numeric)
{
MessageBox.Show("Please enter a valid numeric distance");
}
You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}
If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.
Here is another simple solution
try
{
int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}
You can do it by javascript on client side or using some regex validator on the textbox.
Javascript
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
Textbox (with fixed ValidationExpression)
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
I agree with Int.TryParse but as an alternative you could use Regex.
Regex nonNumericRegex = new Regex(#"\D");
if (nonNumericRegex.IsMatch(txtEvDistance.Text))
{
//Contains non numeric characters.
return false;
}
You can do this way
// Check if the point entered is numeric or not
if (Int32.TryParse(txtEvDistance.Text, out var outParse))
{
// Do what you want to do if numeric
}
else
{
// Do what you want to do if not numeric
}
I have this extension which is kind of multi-purpose:
public static bool IsNumeric(this object value)
{
if (value == null || value is DateTime)
{
return false;
}
if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
{
return true;
}
try
{
if (value is string)
Double.Parse(value as string);
else
Double.Parse(value.ToString());
return true;
}
catch { }
return false;
}
It works for other data types. Should work fine for what you want to do.
if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
{
lblMessage.Text = string.Empty;
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Maroon;
lblMessage.Text = "You have not entered a number";
return;
}
Here's a solution that allows either numeric only with a minus sign or decimal with a minus sign and decimal point. Most of the previous answers did not take into account selected text. If you change your textbox's ShortcutsEnabled to false, then you can't paste garbage into your textbox either (it disables right-clicking). Some solutions allowed you to enter data before the minus. Please verify that I've caught everything!
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
return true;
}
else
{
// If it's not the first character, then it must be a digit or backspace
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
return false;
else
return true;
}
}
else
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
{
// If the first character is a decimal point or digit, AND
// if the text does not contain a decimal point OR the selected text DOES contain a decimal point.
if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
return false;
else
return true;
}
}
else
{
// If it's not the first character, then it must be a digit or backspace OR
// a decimal point AND
// if the text does not contain a decimal point or the selected text does contain a decimal point.
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
return false;
else
return true;
}
}
}
To check if the value is a double:
private void button1_Click(object sender, EventArgs e)
{
if (!double.TryParse(textBox1.Text, out var x))
{
System.Console.WriteLine("it's not a double ");
return;
}
System.Console.WriteLine("it's a double ");
}
I know this is an old question but I figured out I should pitch my answer anyways.
The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.
using System;
private bool ValidateText(string text){
char[] characters = text.ToCharArray();
foreach(char c in characters){
if(!char.IsNumber(c))
return false;
}
return true;
}
Use Regex as below.
if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
MessageBox.show("add content");
} else {
MessageBox.show("add content");
}

Preventing Index Out of Range Error

I want to write a check for some conditions without having to use try/catch and I want to avoid the possibilities of getting Index Out of Range errors
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
So the problem I am facing is that in the second check I need to see whether I have one Item that is not empty. However, If I don't have Element[1], I get the Index Out of Range exception. The problem is that there could be 2 Elements and one(or both) of them may have empty Object arrays. The code will have to be executed only if one of thos Item strings is not empty.
Hopefully, I explained it well. How do I go about avoiding getting that exception under any condition?
Alright, you need some better null checking and some more cautious code here.
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
is just unacceptable.
First, let's null check
if (array != null)
{
if (array.Element != null)
for simplicity, you could use &&
if (array != null && array.Element != null)
then, inside that if, we use a for loop (since you're stuck on arrays) and null check it
for (int i = 0; i < array.Element; ++i)
{
if (array.Element[i] != null && array.Element[i].Object != null)
{
then, since you have nested arrays, we loop again. This is called a nested loop, and it's generally bad practice, I'll show you why it works in a second.
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
Now, with all of that ugly nested loopyness, we've found out that your Item is not null.
On top of that, you have access to ALL of the potential values here, and can group them as you like. Here's how I would put the whole thing together for simplification.
List<string> arrayValues = new List<string>();
if (array != null && array.Element != null)
{
for (int i = 0; i < array.Element.length; ++i)
{
//bool found = false;
if (array.Element[i] != null && array.Element[i].Object != null)
{
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
arrayValues.Add(array.Element[i].Object[o].Item);
//if you want to drop out here, you put a boolean in the bottom loop and break and then break out of the bottom loop if true
//found = true;
//break;
}
}
}
//if (found)
// break;
}
}
if (arrayValues.Count > 0)
{
//do stuff with arrayValues
}
Could use a LINQ method ElementAtOrDefault(index)
so if the element is not found it will be null.
var currentElem = Elems.ElementAtOrDefault(i);
if(currentElem != null)
// do something
else
// do something
Could you do something like:
if(array.Element[0] != null || array.Element[1] != null){
//execute code
}
Your code is probably subject to refactor.
I assume it can work this way:
var obj = array.Element.FirstOrDefault(x => x.Object.Length > 0);
if (obj != null)
{
if (obj.Object[0].Item.Length != 0)
{
// do whatever is necessary
}
}
I think you can put your check in right before your first if Check.
if (array.Length > 1 && array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
This should just short-circuit out if your array doesn't have both Elements.
Place both tests together using the short-circuit && so that the second test doesn't occur if the first fails:
object element0 = array.Element[0].Object;
object element1 = array.Element[1].Object;
// Ensure at least one Object array has a non-empty value.
if ((element0.Length > 0 && !string.IsNullOrEmpty((string)element0.Object[0].Item))
|| (element1.Length > 0 && !string.IsNullOrEmpty((string)element1.Object[1].Item)))
{
// ...
}
I am presuming it is Object[1] causing the exception--you weren't clear on that. If it is Element[1] that causes the exception (or both), then you need to pre-test the length of the array:
if ((array.Element[0].Length != 0 && HasValue(array.Element[0].Object))
|| (array.Element[1].Length > 1 && HasValue(array.Element[1].Object)))
{
// ...
}
// <summary>
// Returns true if the specified string array contains a non-empty value at
// the specified index.
// </summary>
private bool HasValue(System.Array array, int index)
{
return array.Length > index &&
!string.IsNullOrEmpty((string)array.Object[index].Item);
}
for (long i = 0; i <= (output3.Length); i++)
{
output1.WriteByte(output3[i]); -----> index out of range exception correct it
output1.WriteByte(output3rx[i]);
}

checking filename

How can i check if filename contains some string? for example if "frody" contains "ro"?
I tried like that:
if (file_name.Contains("ro")== true)
and:
if (file_name.Contains("ro"))
Both are correct. The second is probably more favoured.
E.g., this returns true:
string s = "test-ro.doc";
Console.WriteLine(s.Contains("ro"));
if (s == null || s.Trim().Length == 0)
{
return false
}
else
{
return s.ToLower().Contains("ro");
}

Categories

Resources