I have a problem with regular expression validation, see If I put the validation in code behind like,
[RegexValidator("[0-9 -]*"
, MessageTemplateResourceName = "INVALID_PHONE"
, MessageTemplateResourceType = typeof(ValidatioinErrors))]
public string Phone
{
get { return phone; }
set { phone = value; }
}
and if I give the value for phone as "080-244408" like this its working but if I give "080-2404408", that is one extra digit it shows error as "Invalid phone". What is the reason. can anyone help me, thanks in advance.
Doesn't look like a problem with your regex. You need to give more information on this. Something else might be wrong in your code.
Related
I am newbee here right now, i'm trying to solve my problem code but it's doesn't clear.
I want to get value from my string textBox.Text. initial textBox is hmI7Segment1.Text. it's has string Format as Channel1.DV1.DB1.Level1. i wish to convert double value from this string into textBoxTarget.Text.
so, here is code problem:
hmI7Segment1.Text = "Channel1.DV1.DB1.Level1";
TextBox txtBoxTarget = converted.Format [hmI7Segment1.Text] as TextBox;
if all of you have solution, please help me to solve my case. thanks for all of you are.
Marbun
So if I understand correctly you wish to convert a value of a textbox which is a string, to a double right?
In that case you can do something like this:
Var stringInput = textbox.Text;
If(double.TryParse(stringInput, out var doubleInput))
{
//Do something with the double value
}
Else
{
//Input is not a valid double value, handle it by showing an error or something
}
Also you didn't specify the technology of your UI, is it forms or wpf?
Hope this helps
Haven't been able to find a good answer to my situation yet. I want this textbox to only take numbers and still have the id "SearchString2" so I can use it in my controller. Any idea how?
if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
{
#:<p><b>Customer ID:</b> #Html.TextBox("SearchString2")</p>
}
Thanks in advance.
You can do something like this:
#Html.TextBox('SearchString2', new { #type = "number" })
This should set the type to be a number, you could then use attributes on your model to help limit it to only ints like so:
[RegularExpression(#"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
public string SearchString2 { get; set; }
You'll need to replace the regex with an actual regex and put an validation message in.
Here's more info on validation: http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation
Actually, I think the correction needed to the above answer is
#Html.TextBox('SearchString2',null, new {#type="number"})
otherwise type=number shows up in the value.
I am trying to convert an object (coming from a SQL server), into a integer so I can format the number to have the correct amount of zero's in front of it.
For example:
If I were to have 25.6, I would need it to be 0025.6.
Now I have looked online on how to do this, but the methods that I have seen people post are not working for me. I am not entirely sure why. I am trying to format GlobalVariables.grossweightafter. I read the value GlobalVariables.grossweight from the SQL server, but then when I TryParse it, it loses its value. The code I have is below:
while (TransferRecord.Read())
{
//Pulling data from the SQL server. getting data for every line of code as specified.
GlobalVariables.baledate = TransferRecord["keyprinter_datetime"];
GlobalVariables.baleline = TransferRecord["pulp_line_id"];
GlobalVariables.baleid = TransferRecord["bale_id"];
GlobalVariables.grossweight = TransferRecord["bale_gross_weight"];
GlobalVariables.grossweightflag = TransferRecord["gross_value_flag"];
GlobalVariables.baleairdrypercent = TransferRecord["bale_airdry_pct"];
GlobalVariables.airdryflag = TransferRecord["airdry_value_flag"];
//Converting the date, and the baleid to fit in the string.
DateTime.TryParse(GlobalVariables.baledate.ToString(), out GlobalVariables.baledateafter);
int.TryParse(GlobalVariables.baleid.ToString(), out GlobalVariables.baleidafter);
int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter);
GlobalVariables.grossweightafter.ToString("0000.0");
//Calling the WriteData method.
WriteData();
}
So I was wondering if anyone can catch what I am doing wrong, or they can help me out on the correct way to go about this.
What #Hans Passant was saying is that you need to assign the value returned from .ToString. That line should be:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
The last lines should be
if(int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter))
{
string grossWeightAfter = GlobalVariables.grossweightafter.ToString("0000.0");
//you need to save the string returned from the ToString-method somewhere or it will be lost.
///Alternatively, if GlobalVariables can contain strings aswell:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
}
else
{
//React on value not being an int
}
Maybe you should try to use double.TryParse() method instead of int.TryParse(), because int does not have fractional part?
Also, you need to store ToString() result to a string variable. Your code should be like this:
GlobalVariables.grossweightafterstring = GlobalVariables.grossweightafter.ToString("0000.0");
I'm using a MaskedTextBox, with the following short date Mask: "00/00/0000".
My problem is that I wanna know when the control is empty:
if (string.IsNullOrEmpty(maskedTextBox1.Text))
{
DataTable dt = function.ViewOrders(Functions.GetEid);
dataGridView2.DataSource = dt;
}
It's not working, when maskedTextBox1 looks empty (and I'm sure it is), the if statement doesn't detect that it is null or Empty.
You can simply use:
maskedTextBox1.MaskCompleted
Or
maskedTextBox1.MaskFull
properties to check if user has entered the complete mask input or not.
I know this is old but I would first remove the mask and then check the text like a normal textbox.
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
//...Perform normal textbox validation
I just faced this problem. I Needed the Masked Value, but also needed send empty string if the user didn't introduced any data in one single step.
I discovered the property
MaskedTextProvider.ToDisplayString so I use the MaskedTextbox with:
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
BUT I always read the text from:
maskedTextBox.MaskedTextProvider.ToDisplayString()
This way, if the user has not introduced text in the control Text property will be empty:
maskedTextBox.Text == string.Empty
And when you detect the string is not empty you can use the full text including literals for example:
DoSomething((maskedTextBox.Text == string.Empty) ? maskedTextBox.Text: maskedTextBox.MaskedTextProvider.ToDisplayString());
or
DoSomething((maskedTextBox.Text == string.Empty) ? string.Empty: maskedTextBox.MaskedTextProvider.ToDisplayString());
If you set the property maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals then the TypeValidationCompleted event validation will not work. To test if the short date maskedtextbox is empty you could just use:
if (maskedTextBox1.Text == " / /")
{
...;
}
Did you try trim.
if(string.IsNullOrEmpty(maskedTextBox.Text.Trim())
What logic are you trying to accomplish with the if statement? As it is right know, you are saying:
If the textbox is empty, set source of datagridview2 + to ViewOrder data. I'm not sure what your trying to do but I think you want the info to load if you have a date. to fix this all you have to do is add ! in the if statement which would make the if statement mean, if there is text in textbox then run code.
if( !(string.IsNullOrEmpty(maskedTextBox2.Text)))
In case of Telerik masked textbox which does not have MaskCompleted or MaskFull, a tricky solution would be this:
the mask always contain a charachter like this: "_" we check masked text box by this:
if (textbox1.Text.Contains("_"))
{
MessageBox.Show("Please enter the correct numbers!","Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);
return;
}
if the text box is full, then it does not contain "_".
I believe the MaskedTextBox, (MTB), using the mask “00/00/0000” is an incorrect string to use for testing its emptiness. This is because the MTB is not like a normal textbox, and the short date mask must be used to determine its string value.
Let’s assume you have a MTB name mskDateOfBirth on your form. In order to test its emptiness, a statement like the following is needed
if (mskDateOfBirth.MaskedTextProvider.ToDisplayString() == "__/__/____")
{
// Do something when true
}
else
{
// Do something when false
}
I have tested this out using Visual Studio 2019 and it works fine. Hope this is helpful.
If the empty value is " / /", declare a constant for it:
const string EmptyDateInput = " / /";
And then later you can repeatedly use it to compare:
if (maskedTextBox1.Text == EmptyDateInput)
{
}
I test this concept and was success in in the following syntax
if( maskedtextbox_name.MaskkedTextProvider.ToDisplayString() == "__-__-____")
{
// Your function;
}
am looking for the regular expression of indian phone number
the regular expression should allow all the following formats.
for landline no
0802404408
080-2404408
+91802404408
+91-802404408
for mobile no
8147708287
08147708287
+918147708287
+91-8147708287
can anyone help me, thanks in advance
my code is
[RegexValidator("[0-9 -]*"
, MessageTemplateResourceName = "INVALID_PHONE"
, MessageTemplateResourceType = typeof(ValidatioinErrors))]
public string Phone
{
get { return phone; }
set { phone = value; }
}
public bool IsValid()
{
return Validation.Validate<Class_name>(this).IsValid;
}
public ValidationResults ValResults
{
get
{
return Validation.Validate<Class_name>(this);
}
}
for this validation thing I just referred
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
in my namespace, in the UI part the expression is working fine, but in the code behind as above, it shows "Invalid Phone number", if I give value as 080-2404408
You can try
^\+?[0-9-]+$
See it here on Regexr
The important parts are the anchors ^ and $ for the start and the end of the string. I added also \+? at the start, to match an optional +. The + needs to be escaped since it is a special character in regex, the ? after it makes it optional.
Of course this is a very simple pattern, be aware that e.g. "-----" would also be valid.
For the examples provided following RegEx works:
/^(?:\+91(?:-)?|0\d{2,4}-|0|)\d{7,10}$/
import re
mystr = """
8147708287
08147708287
+918147708287
+91-8147708287
"""
print(re.findall(r'\b91-*\d{10}',mystr))