can I make my text box to allow only L & P for the starting two letters that is entered by a user.. example: LP12345678901. I hope the example makes the question specific...
I tried this
if(myTextBox.Text.StartsWith("LP"))
I tried regex too... but we cant be specific in alphabets right?
Try this code:
private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (myTextBox.Text.Length == 2)
{
if (myTextBox.Text.StartsWith("LP"))
{
//yourcode
}
else
{
myTextBox.Text = string.Empty;
}
}
}
This will help you.
function Valid() {
var re = "^[LP][0-9]{11}$";
var str = document.getElementById("txtTSection").value;
var myArray = str.match(re);
if (myArray == null) {
alert("Incorrect Format");
$("#txtTSection").css("border-color", "red");
return false;
}
else {
$('#txtTSection').css('border-color', '');
}
}
<asp:TextBox ID="txtTSection" runat="server" CssClass="form-control" TabIndex="1" MaxLength="13" onfocusout="Valid()" ></asp:TextBox>
This is not a technical solution, but rather an UX suggestion:
If I always have to enter "LP" as the first letters and I'm not allowed to enter different letters or numbers, then don't make me enter them every time. You already decided that "LP" are the first two letters. There is no point in me typing it again. I cannot gain anything good from it. Even if I'm perfect entering it, the best result I can achieve is "no error message".
If your first two letters have to be "LP" then put "LP" as a label before the textbox and make the user only enter the digits. When you are working with what the user entered, prefix it with "LP".
public static bool ValidateSerNo(string ser)
{
if (!string.IsNullOrEmpty(ser))
{
if (ser.Trim().Length == 11)
{
if (ser.Trim().ToUpper().Substring(0, 2) == "LP")
{
if (Microsoft.VisualBasic.Information.IsNumeric(ser.Substring(2, 9)))
{
return true;
}
}
}
}
return false;
}
private void btn_Save_Click(object sender, EventArgs e)
{
if ((BattVoltMmnt.ValidateSerNo(txtbox_Serialno.Text.Trim().ToUpper()) == false))
{ MessageBox.Show("Enter correct serial number");
}
}
Related
I'm checking the user ID in the text box. And it can not start with a letter or digit '0'. I can catch the wrong entry and send a message to the screen. But the wrong entry will be in the text box until I hit another key. And if this is an acceptable digit then the wrong entry stays at the beginning of the string. So I need to get rid of the wrong entry immediately after the message dialog box. Any suggestion?
private void TxtUserID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
MessageBox.Show(" Your User ID can not begin with a letter !!!");
//txtUserID.Text = string.Empty;
txtUserID.Clear();
}
else if (e.KeyChar == '0')
{
MessageBox.Show("Your User ID can not begin with 0 !!!");
txtUserID.Text = string.Empty;
}
}// end of keypress
I suggest using TextChanged instead of KeyPress event: whatever changed TxtUserID.Text (e.g. Paste, or, imagine, user put "12340" and then deleted "1234" in order to obtain "0") validate the TxtUserID
private static bool IsNameValid(string name) {
if (string.IsNullOrEmpty(name))
return true;
else if (name.Any(c => c < '0' || c > '9')) {
MessageBox.Show("Your User ID must contain digits only!");
return false;
}
else if (name.StartsWith("0")) {
MessageBox.Show("Your User ID must not start from 0!");
return false;
}
return true;
}
private void TxtUserID_TextChanged(object sender, EventArgs e) {
if (!IsNameValid(TxtUserID.Text))
txtUserID.Clear(); // Taken from the question
}
Edit: As Thomas Voß pointed out, clearing the entire text can be to cruel for a user (imagine that he's printed "1001234566978563" and then decided to remove leading "100"), probably
txtUserID.Text = string.Concat(txtUserID
.Text
.Where(c => c >= '0' && c <= '9') // Digits only
.SkipWhile(c => c == '0')); // Trim all starting '0'
instead of txtUserID.Clear(); when we remove all characters but digits and trim leadibng 0 is a better choice.
So one of the forms I have to create is where you enter a first and last name and then it splits the two names and puts them next to the appropriate labels, form design: https://gyazo.com/9b34dca0c1cd464fd865830390fcb743 but when the word stop is entered in any way e.g. Stop, StOp, sToP etc. it needs to end.
private void btnSeparate_Click(object sender, EventArgs e)
{
string strfullname, strgivenname, strfamilyname, strfirstname;
int int_space_location_one, int_space_location_two;
strfullname = txtFullName.Text;
int_space_location_one = strfullname.IndexOf(" ");
strgivenname = strfullname.Substring(0, int_space_location_one);
lblGivenEntered.Text = strgivenname;
strfirstname = strfullname.Remove(0, int_space_location_one + 1);
int_space_location_two = strfirstname.IndexOf(" ");
strfamilyname = strfirstname.Substring(int_space_location_two + 1);
lblFamilyEntered.Text = strfamilyname;
}
This is my current code, I have tried many different ways to get the word stop to end it but it wont work so that's why there is currently no code trying to stop the program, the main problem I get is because it is searching for a space between the first and last name and it obviously doesn't have one for one word it just crashes.
Any help with this would be amazing, thanks in advance.
Just hook up the TextChanged event and go like this:
private void TextChanged(Object sender, EventArgs e)
{
// If text, converted to lower-characters contains "stop" -> Exit
if(txtFullName.Text.ToLower().Contains("stop"))
{
// What I understand as "stopping it".
Application.Exit();
}
}
IF with "stop it" you mean to cancle the operation:
private void btnSeparate_Click(object sender, EventArgs e)
{
// If text, converted to lower-characters contains "stop" -> Exit
if (txtFullName.Text.ToLower().Contains("stop"))
{
// What I understand as "stopping it".
Application.Exit();
}
else
{
// Your code inside the else block
}
}
Short version of everything: Also covering no spaces problem
private void btnSeparate_Click(object sender, EventArgs e)
{
// Save how many words are inside
int wordsInText = txtFullName.Text.Split(' ').Length;
// Save if "stop" was typed into the textbox
bool stopExisting = !txtFullName.Text.ToLower().Contains("stop");
// If text has exactly 3 words and "stop" is NOT existing
if (wordsInText == 3 && !stopExisting)
{
// Save array of splitted parts
string[] nameParts = txtFullName.Text.Split(' ');
// This is never used??
string strfirstname = nameParts[1];
// Set name-parts to labels
lblGivenEntered.Text = nameParts[0];
lblFamilyEntered.Text = nameParts[2];
}
// If text has NOT exactly 3 words and "stop" is NOT existing
else if(wordsInText != 3 && !stopExisting)
{
// If there are no 3 words, handle it here - MessageBox?
}
// If "stop" IS existing
else if(stopExisting)
{
// If text contains "stop" handle it here
// Application.Exit(); <-- if you really want to exit
}
}
You could just check, if one of the entered words is equal to the word "stop". There you need a StringComparions which ignores the case. Or you could parse the entered word into lower/upper-cases.
So if the check is true, you could just end the program with
Environment.Exit(0);
You could just check, if one of the entered words is equal to the word "stop". There you need a StringComparions which ignores the case. Or you could parse the entered word into lower/upper-cases.
So if the check is true, you could just end the program with
Environment.Exit(0);
Code:
if (strfullname.ToLowerInvariant().Contains("stop"))
{
Environment.Exit(0);
}
I have a simple form that takes 9 decimal numbers from 9 textboxes and I put some validation so that the users can only enter decimal numbers and nothing else.
Now the challenge I'm having is how to set the cursor in the textbox that had no decimal number after showing the error message in the try-catch statement?
Here's my code:
private void btn_Aceptar_Click(object sender, EventArgs e)
{
POI GPI = new POI();
POI VIM = new POI();
POI ST = new POI();
try
{
GPI.POI_x = Convert.ToDecimal(txt_GPIx.Text);
GPI.POI_y = Convert.ToDecimal(txt_GPIy.Text);
GPI.POI_z = Convert.ToDecimal(txt_GPIz.Text);
VIM.POI_x = Convert.ToDecimal(txt_VIMx.Text);
VIM.POI_y = Convert.ToDecimal(txt_VIMy.Text);
VIM.POI_z = Convert.ToDecimal(txt_VIMz.Text);
ST.POI_x = Convert.ToDecimal(txt_STx.Text);
ST.POI_y = Convert.ToDecimal(txt_STy.Text);
ST.POI_z = Convert.ToDecimal(txt_STz.Text);
}
catch (Exception)
{
MessageBox.Show("Ingrese solamente números en las variables GPI/VIM/ST", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Set the cursor in the first textbox that had no decimals..
return;
}
Comisurales Comisurales = new Comisurales();
Comisurales.calculo_coord_comisurales(PC, AC, IHP, GPI, VIM, ST);
}
Let me add that I also have a function to ensure the user is only limited to enter decimals but I wasn't able to figure how to avoid the "." only or this for example: "1."
As an addition to my question, here's what gets validated every time the user press a key in the textbox:
private void ValidarDecimal(object sender, KeyPressEventArgs e)
{
// permitir 0-9, backspace, y decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// chequear solamente un decimal
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
I guess I have 2 ways to resolve my issue. Number one would be find a way to ensure the user never ever enters something weird in the textbox (which I've done partially) and number 2 would be to use the try-catch with the current limitations I mentioned above and then point the user to the textbox that has issues, both are acceptable.
The Decimal class has a TryParse method that could be used to avoid all this logic driven by catching exceptions (a very expensive approach in terms of performance)
decimal value;
if(decimal.TryParse(txt_GPIx.Text, out value))
GPI.POI_x = value;
else
{
MessageBox.Show("Invalid decimal value");
txt_GPIx.Focus();
}
Of course this code needs to be repeated for every control in your list, but you could write a generic function like this one
private decimal GetValueAndValidate(Textbox txt, out bool isOK)
{
isOK = true;
decimal value = 0m;
if(!decimal.TryParse(txt.Text, out value))
{
MessageBox.Show("Invalid decimal value");
txt.Focus();
isOK = false;
}
return value;
}
and then use the following approach in your code inside the button click
bool isOK = true;
if(isOK) GPI.POI_x = GetValueAndValidate(txt_GPIx, out isOK);
if(isOK) GPI.POI_y = GetValueAndValidate(txt_GPIy, out isOK);
.... and so on for the other fields ....
For the second part of your question, finding a way to completely control the input logic is not easy. What happens for example if your user PASTE an invalid text in your textbox? There are very edge case situations that takes a lot of effort to code correctly. It is a lot more easy to leave freedom of typing to your user and apply a strict logic when you get that input.
I have written a little program. It works almost as I want, I just have one problem. I am trying to copy all functions I have found in the other program.
I have a TextBox, when the user can write a phone number. Firstly, he is only allowed to use digits and "+"and "-", so I use:
private void textBoxPhoneNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char.IsDigit(e.KeyChar) == false) && (e.KeyChar != '+') && (e.KeyChar != '-') && (e.KeyChar != '\b')) e.Handled = true;
}
Then I want the phone number to be in certain format (+12-34-1234567), so I use:
private bool IsPhoneNumberCorrect(string name)
{
return Regex.IsMatch(name, #"^+\+[0-9]{2}-[0-9]{2}-[0-9]{7}$", RegexOptions.None);
}
and finally this (with TextChange):
private void phoneNumberValidity(object sender, EventArgs e)
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
checkIfOk();
textBoxPhoneNumber.Focus();
}
I use counter4 as a part of method (checkIfOk) that enables button. There is also an "X" icon that changes into "tick" when the number is given in proper format.
It works perfectly for me (just like in the program I am copying) - when the user writes something in the TextBox, he can only use digits and "+" and "-" and when the format is ok the icon changes and when other textboxes are also ok, the Ok buton enables.
Now, finally, the problem:
I am able to paste something from the Clipboard. In the original program, when I paste something with letters, digits and other signs, only digits and "+" and "-" remains. My program accepts everything in such situation.
I've been looking for something that might be helpful, but all I have found was very complicated. Is there a way to do it?
I tried to do something like this. It causes that when pasting only digits and "+" and "-" remains as it should, but the user can't write anything.
I am still a beginner. Maybe I am making a simple mistake?
private void phoneNumberValidity(object sender, EventArgs e)
{
Regex regex = new Regex("[^0-9-+]");
if (regex.IsMatch(Clipboard.GetText()))
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
string output = regex.Replace(Clipboard.GetText(), "");
textBoxPhoneNumber.Text = output;
checkIfOk();
textBoxPhoneNumber.Focus();
}
}
I am trying to do something like this:
private void phoneNumberValidity(object sender, EventArgs e)
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
checkIfOk();
textBoxPhoneNumber.Focus();
Regex regex = new Regex("[^0-9-+]");
if (textBoxPhoneNumber.Text.Contains("a"))
{
if (regex.IsMatch(Clipboard.GetText()))
{
string output = regex.Replace(Clipboard.GetText(), "");
textBoxPhoneNumber.Text = output;
}
}
}
I know that it's not exactly what I want, but maybe someone can give some clues...
Generally i thought, that I'd like to check if the text in tb contains some unwanted elements, but I don't know how to check it. As you can see, it checks only one unwanted element.
First of all, please use TRY-Catch for the Convert.ToInt32 !
Second: Use TextChanged event, and validate the input with the actual content of the TextBox
To validate, you can do something similar:
string output = ""
string clipboardText = GetClipboardText()
for each chara in clipboardText's characters
if chara.isNumeric or chara=='+' or chara == '-'
output += chara
end foreach
Of course its just a simple soultion, but you can confgure it as you want.
Or if you want more complex way, you can play with the regex... Start with number or + - BUT not contains alphabetical char. Based on your request.
This is what I made, and it works :) I will only add try-catch block as Krekkon has suggested.
private void phoneNumberValidity(object sender, EventArgs e)
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
if (Regex.IsMatch(textBoxPhoneNumber.Text, "[^0-9-+]"))
{
Regex regex = new Regex("[^0-9-+]");
string output = regex.Replace(Clipboard.GetText(), "");
textBoxPhoneNumber.Text = output;
}
checkIfOk();
textBoxPhoneNumber.Focus();
}
Maybe it will help someone in the future.
Maybe you should try like this: leave the first version of phoneNumberValidity method as it is and then check if the tb Text has some unwanted elements, get rid of them.
I have a label and I want it to display either Player or Console depending on what the variable answer is.
private void playerLabel_Click(object sender, EventArgs e)
{
string playerDetail = "Player",
consoleDetail = "Console";
if (Class.Method.Variable == 1)
{
Show.playerDetail();
}
if else (Class.Method.Variable == 0)
{
Show.consoleDetail();
}
}`
I then want to make it so that the label shows the string instead if you get me. I know I am not doing this properly but I can't work out how exactly to do this.
private void playerLabel_Click(object sender, EventArgs e)
{
string labelText = playerLabel.Text;
if (Class.Method.Variable == 1)
{
labelText = "Player";
Show.playerDetail();
}
else if(Class.Method.Variable == 0)
{
labelText = "Console";
Show.consoleDetail();
}
playerLabel.Text = labelText;
}
It would be better if your methods in Show class returned the appropriate string, so that you can do: playerLabel.Text = Show.WhateverDetail();. Additionally its even better if you could tie the Show method with the Variable value so that you don't have to use an if-else logic at all.
a. The Text property of the Label is what you want to set your strings to.
playerLabel.Text = playerDetail;
playerLabel.Text = consoleDetail;
b. Your if/else method should be in the form of:
if (test)
{
}
else if
{
}
else
{
}
You don't need the else if bit in the middle if there are only two branches.
c. I'm not sure about Show.consoleDetail() and Show.playerDetail(). Are 'consoleDetail()' and 'playerDetail()' method calls?