开发者

c#3.5 textbox validations

开发者 https://www.devze.com 2023-02-11 09:29 出处:网络
I am usingC# 3.5 and I have a problem in my project, I want to make a text box to accept only numbers. If a user tries to enter characters, a message should appear like \"please enter numbers only\",a

I am using C# 3.5 and I have a problem in my project, I want to make a text box to accept only numbers. If a user tries to enter characters, a message should appear like "please enter numbers only",and in another textbox it has to accept valid email id message should appear when it is invalid. It has to show invalid 开发者_如何转开发user id.


For the "only numbers" validation you can use the CompareValidator in Operator="DataTypeCheck"

<asp:CompareValidator runat="server" ErrorMessage="Only numbers" 
Type="Integer" ControlToValidate="YourOnlyNumbersTextBoxID" Operator="DataTypeCheck"/>

For the "email" validation you are probably best off using a RegularExpressionValidator

<asp:RegularExpressionValidator runat="server" ErrorMessage="Invalid email"
ControlToValidate="YourEmailTextBoxID" ValidationExpression="[regex here]"/>


function onlyNumbers(evt)
{    
  var e = event || evt; 
// for trans-browser compatibility    
  var charCode = e.which || e.keyCode;    
  if (charCode > 31 && (charCode < 48 || charCode > 57))        
      return false;    
  return true;
}

use the above function and apply it to the onkeypress event of the textbox, the above is a javascript, and for the another text box use Required Field Validator it will work. Hope this will help u.


you can use validation control and then regular expression
For number you can use CompareValidator

<asp:CompareValidator ID="CompareValidator1" runat="server" 
 ErrorMessage="CompareValidator" Operator="DataTypeCheck"   Type="Integer"></asp:CompareValidator>


and for email RegularExpressionValidator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>


In both the situations, you would need to define the validation routine in the event handler of the button ( I am assuming there is some kind of button).

There are other ways to achieve this, but this is the simplest.


usually in this case you could use the KeyDown event and cancel it if the key pressed is not a number. I would not show an alert to the user, he/she will see that only numbers are accepted.


public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar);
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消