how to use RegularExpressionValidator on textbox - asp.net

I have an text box i need to validate so that the user can enter enter up to four character and they can be alphanumeric. I am using VS2003, .NET 1.1.
Please let me know what is the expression i should use to validate this condition
any help would be great. Thanks!
Tried like this:
<asp:TextBox id="wtxtTPP" tabIndex="2" runat="server" CssClass="text" Width="144px" MaxLength="4" />
<asp:RegularExpressionValidator id="RegularExpressionValidator1" style="z-index: 101; left: 208px; position: absolute; TOP: 16px" runat="server" ErrorMessage="RegularExpressionValidator" ValidationExpression="^([\S\s]{0,4})$" ControlToValidate="wtxtTPP" />
<input style="z-index: 102; left: 88px; position: absolute; top: 72px" type="submit" value="Submit" id="Submit1" name="Submit1" runat="server">

As you said, use a Regular Expression Validator and set the expression to something like this:
^([\S\s]{0,4})$
Replace the 4 with your desired max length.
Update:
<asp:TextBox id="wtxtTPP" Runat="server" />
<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server"
ErrorMessage="RegularExpressionValidator"
ValidationExpression="^([\S\s]{0,4})$"
ControlToValidate="wtxtTPP" />
<asp:Button ID="Button1" runat="server" Text="Button" />
This works just fine for me. I replaced your submit button with a normal asp.net button and simplified out all the unneeded stuff for the example.
In general, if you only have a one line textbox, you can just limit the text length with MaxLength="4" as you did. No need for a Validator.

Like #Remy said.
Also, the {0,4} part of the Regexp means length should be zero to a max of four so will allow for zero-length, i.e. no input. Remember to use a RequiredFieldValidator if the number is mandatory or replace the zero with a minimum number of digits.

<table>
<tr>
<td>E-mail Address:</td>
<td>
<asp:TextBox ID="txt_address" runat="server"></asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat ="server"
ErrorMessage="Please give Email Address! "
ControlToValidate="txt_address"
ValidationExpression="\S+#\S+\.\S+\w+"//example (example#yahoo.com)
ForeColor="Red" >
</asp:RegularExpressionValidator>
</td>
</tr>
</table>
<table>
<tr>
<td>
<asp:RadioButtonList ID="rbl_gender" runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldVlidator2" runat="server"
ErrorMessage="Please Choose your Gender" ControlToValidate="rbl_gender"
ForeColor="Red" >
</asp:RequiredFieldValidator>
</td>
</tr>
</table>
<table>
<tr>
<td>
<asp:RequiredFieldValidator ID="RequiredFeildValidator1"
runat ="server" ControlToValidate ="txt_name"
ErrorMessage="Please Insert Your name !"
ForeColor="Red">
</asp:RequiredFieldValidator>
</td>
</tr>

A very small change in the ValidationExpression seems to make the difference between only sometimes working, and reliably working.
The following worked for me in development, but not in production:
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "tbCarePlan" ID="revCarePlan" ValidationExpression = "^(.{0,4000})$" runat="server" ErrorMessage="Max 4000 characters allowed." />
Replacing the ValidationExpression above with "[\s\S]{0,4000}" it now works reliably. Leave out the ^ and $ - the RegularExpressionValidator does not require this.

Related

ASP.NET validator never validates as true

The code below has always worked, but now somehow I can't submit the form anymore even though I provide both username and password. I get no errors in backend or the Chrome Developer Console. I tried enabling/disabling all validators and found that if I add Enabled="false" to validator UserNameRequired, the form does submit. But obviously I want to have this requiredfieldvalidator enabled.
Why is this happening?
You can also see it live here (fill in a random email address/password): http://www.zorgbeurs.nl/login
<table width="300">
<tr>
<td>
<asp:Label ID="UserNameLabel" Text="Email" runat="server" AssociatedControlID="UserName"/>
</td>
<td>
<asp:TextBox ID="UserName" Text="" runat="server" Width="160px"/><br />
<asp:RequiredFieldValidator Enabled="false" ValidationGroup="loginuser" Display="Dynamic" SetFocusOnError="True" ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="*"/>
<asp:RegularExpressionValidator ControlToValidate="UserName" ValidationGroup="loginuser" ErrorMessage="Ongeldig emailadres" ValidationExpression="<%$resources:glossary,regexValidEmail %>" ID="revUsername" runat="server" Display="Dynamic"/>
</td>
</tr>
<tr>
<td valign="top">
<asp:Label ID="PasswordLabel" Text="<%$ Resources:Glossary,Password%>" runat="server" AssociatedControlID="Password"/>
</td>
<td valign="top">
<asp:TextBox ID="Password" runat="server" TextMode="Password" Width="160px"/><br />
<asp:RequiredFieldValidator Enabled="false" SetFocusOnError="True" Display="Dynamic" ValidationGroup="loginuser" ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="*" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:ImageButton CausesValidation="true" ValidationGroup="loginuser" ID="LoginMember" meta:resourcekey="ibtnLogin" CommandName="Login" runat="server"/>
<asp:CheckBox TextAlign="Right" CssClass="cblist" Font-Bold="false" ID="RememberMe" runat="server" Text="<%$ Resources:Glossary,loginrememberme%>" /><br />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="FailureText" runat="server" ForeColor="Red" Font-Bold="true" EnableViewState="False"/>
</td>
</tr>
</table>
update
I also tried adding the ValidationExpression of revUsername expression directly in the code [-+.'\w]+#[-.\w]+\.[-.\w]+, but that does not help.
I can see the required validators working in your live site without making a postback.
Regarding the email's regular expression validator, it seems that your expression is not working properly. So, I suggest you to change your regular expression, try this one:
<asp:RegularExpressionValidator Enabled="true" ControlToValidate="UserName"
ValidationGroup="loginuser" ErrorMessage="Ongeldig emailadres"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ID="revUsername" runat="server" Display="Dynamic" />
Also, remember to enable it again in order to make it work both on client and server side.
Hope it can help you!

Field Validator

In the code below, the submit buttion has the 'SubmitValidation' ValidationGroup.
When i change the name of the ValidationGroup in the RequiredFieldValidator (to submitValidation123), the Error Message 'Enter State Code' does not appear (as expected). However, the submit does not take place till I actually enter a value for the state code. WHY?
<tr>
<td>
<span class="requiredText">*</span> State Code (Ex. TX):
</td>
<td>
<asp:TextBox runat="server" ID="statecodeTxt" Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="statecodeRFV" runat="server"
Display="Dynamic" ValidationGroup="submitValidation"
ControlToValidate="statecodeTxt" SetFocusOnError="True"
ErrorMessage="Enter State Code" />
</td>
</tr>
<asp:Button ID="submitBtn" Text="Submit" disabled="true"
runat="server" ValidationGroup="submitValidation"
OnClick="submitBtn_Click" />
Try remove or make false the
SetFocusOnError="True"

2 validators validate one at a time

Hi I have a change password page.
I have 2 textboxes, New Password and Confirm Password.
Both have a requiredFieldValidators.
And a compareValidator.
But what happens is when I key in the first field New Password, the second textbox's requiredFieldValidator and CompareValidator are showing error messages at the same time.
I only want to show requiredFieldValidator and only when that validator returns true, I want to validate compareValidator.
How can I achieve that. The following is my code.
<table class="editAccTable">
<tr>
<td>
New Password<br />
<asp:TextBox ID="txtNewPwd" runat="server" TextMode="Password" Width="204px"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="rfvNewPwd" runat="server"
ControlToValidate="txtNewPwd"
ValidationGroup="vgChangePwd"
Display="Dynamic"
></asp:RequiredFieldValidator>
</td>
<td>
Confirm New Password<br />
<asp:TextBox ID="txtConfPwd" runat="server" TextMode="Password" Width="204px"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="rfvConfPwd" runat="server"
ControlToValidate="txtConfPwd"
ValidationGroup="vgChangePwd"
Display="Dynamic"
></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvChangePwd" runat="server"
ValidationGroup="vgChangePwd"
ControlToValidate="txtNewPwd"
ControlToCompare="txtConfPwd"
ValueToCompare="String"
Display="Dynamic"
></asp:CompareValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:ImageButton ID="ibtnPwdChange" runat="server"
ImageUrl="/images/submit.jpg" onclick="ibtnPwdChange_Click"
ValidationGroup="vgChangePwd"
Width="90px" Height="36px"
/>
<br />
<asp:Label ID="lblSuccessPwdChange" runat="server"></asp:Label>
</td>
</tr>
</table>
There is a couple of work around.
For my case, I can remove the requiredFieldValidator for the second textbox as it is enough to have only compareValidator.
But there will be some cases, that there must have 2 validators. In that case, we can use css to overlap the 2 validators.
Try CompareValidator like this
<asp:CompareValidator id="cvChangePwd" runat="server" ControlToValidate="txtConfPwd" ControlToCompare="txtNewPwd" ErrorMessage="Your passwords do not match up!" Display="Dynamic" />
set display property as dynamic
display="dynamic" in all the validators

Validation summary AutoUpdate

In my asp.net application, I've tried to use validation summary in my web page.I've controls like
<td>First Name *</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<div>
<asp:RequiredFieldValidator ID="reqValStaffFirstName" runat="server"
ErrorMessage="Enter FirstName" Text="*"
ControlToValidate="txtFirstName" Display="Dynamic"
ValidationGroup="valGrpStaffGeneral">
</asp:RequiredFieldValidator>
</div>
</td>
<td>Last Name *</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<div>
<asp:RequiredFieldValidator ID="reqValStaffLastName" runat="server"
ErrorMessage="Enter LastName" Text="*"
ControlToValidate="txtLastName" Display="Dynamic"
ValidationGroup="valGrpStaffGeneral">
</asp:RequiredFieldValidator>
</div>
</td>
<td>
<asp:Button Id="btnSave" runat="server" ValidationGroup="valGrpStaffGeneral">
<td>
and my validationsummary script is
<asp:ValidationSummary ID="summary1" ShowSummary="true" runat="server"
ValidationGroup="valGrpStaffGeneral" DisplayMode="BulletList" />
If I click on save button without filling anything in textbox1 and textbox2 its showing validation errors in my validation summary area. If I fill anything in my textboxes and press tab the error(*) disappears automatically, but the error in the validation summary not changing automatically and its displaying until I click on save button, what should I do to make the validation summary change the fixed errors automatically.
This might be of help - look at the EnableClientScript property of the ValidationSummary control.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.validationsummary.enableclientscript.aspx

Putting the cursor in text box after validating in ASP.NET

I have a basic ASP.NET website which has a register page with the user name, password and email as text boxes. Only one of them, the email, has a validation which is the default email validation from ASP.NET.
After the validation, I want the cursor to be in the email textbox if the validation fails.
Currently the message is displayed but the cursor is not on the page.
<tr>
<td>
<asp:TextBox ID="txtPassword" runat="server" CssClass="cpTextBox" TextMode="Password"
TabIndex="7" ToolTip="Password must be at least six characters in length"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Please enter password" Display="None">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revPassword" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Password must be at least six characters in length" ValidationExpression=".{6,50}"
Display="None">*</asp:RegularExpressionValidator>
</td>
<td>
<asp:TextBox ID="txtTitle" runat="server" CssClass="cpTextBox" TabIndex="11"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblVerifyPassword" runat="server" CssClass="cpLabel" Text="Verify password"></asp:Label>
<asp:Label ID="Label4" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:Label ID="lblPhone" runat="server" CssClass="cpLabel" Text="Phone"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtVerifyPassword" runat="server" CssClass="cpTextBox" TextMode="Password"
TabIndex="8"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvConfirmPassword" runat="server" ControlToValidate="txtVerifyPassword"
ErrorMessage="Please verify the password" Display="None">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvVerifyPassword" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtVerifyPassword" ErrorMessage="Please verify the password"
Display="None">*</asp:CompareValidator>
</td>
Can someone guide me on how to do this?
Regards.
For the validator control please set SetFocusOnError="true"

Resources