Validation of three text boxes, including phone number
How do I add ASP.NET validation in C# all three text boxes aren't empty and the phone number has the format of DDDD-DDDD where D is 0 – 9?
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtPhoneNumber" runat="server"></asp:Tex开发者_如何转开发tBox>
Have you tried to solve this problem yourself? The documentation is easy to find:
http://msdn.microsoft.com/en-us/library/aa479013.aspx
You need to use a required field validator -- something like this:
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server"
ErrorMessage="Required!"
ControlToValidate="txtFirstName">
You will also want a regular expression validator, something like:
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server" ControlToValidate="txtPhoneNumber"
ErrorMessage="wrong!"
ValidationExpression="^\d\d\d\d-\d\d\d\d$">
</asp:RegularExpressionValidator>
NB The toolbox for reg expression has many built in, including most phone number formats. I would just use one of those.
Use RequiredFieldValidator and ReguralExpressionValidator controls.
The RequiredFieldValidator server control makes sure that the user enters something into the field that it is associated with in the form. You need to tie the RequiredFieldValidator to each control that is a required field in the form.
The RegularExpressionValidator server control is a validation control that enables you to check the user's input based on a pattern defined by a regular expression.
Refer to:
Validating ASP.NET Server Controls
Markup:
<table>
<tr>
<td><asp:TextBox ID="txtFirstName" runat="server" /></td>
<td><asp:RequiredFieldValidator runat="server" ControlToValidate="txtFirstName" Display="Dynamic" ValidationGroup="group"></asp:RequiredFieldValidator></td>
<td><asp:RegularExpressionValidator runat="server" ControlToValidate="txtFirstName" ValidationExpression="..." Display="Dynamic" ValidationGroup="group">*</asp:RegularExpressionValidator></td>
</tr>
<!-- do the same 2 times more -->
</table>
The RegEx should be I guess:
^\d{4,4}-\d{4,4}$
or (if you don't want to make a variable number of digits, e.g. 2 to 4):
^\d\d\d\d-\d\d\d\d$
what means:
line begin
4 digits, not more or less
dash
4 digits, not more or less
line end
精彩评论