ASP.NET validate - asp.net

I want to validate an asp.net texbox with min char=3, max=10 and no special characters. I do not want to use a plugin of jQuery but plain jQuery
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
How do I about it.
P.S - I asked the question earlier then edited it, but can't find the question now. Seems like it did not get posted.

In asp.net you can use the validate control.
Either a custom validator or a reg ex validator.
Something like this
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Error error..."
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Static" ></asp:RegularExpressionValidator>

Why not use a RegularExpressionValidator with the Regex pattern "[\w]{3, 10}" ?

Related

ASP.NET Regular Expression Validator VS Required Field Validator OR both?

I don't really know if I should be using both the Regular Expression Validator and Required Field Validator or what? I have just a normal form in ASP.Net (Visual Studio). I want to make sure the user types in the correct characters, such as for a phone number (which is why I want the reg ex control), but I also want the field to be required. So should these be combined or what is the best way to do this?
Right now I just have the required part working, like this:
<asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator2"
controltovalidate="TextBoxLocation" errormessage="Required"
/>
You can use both of them, but make sure to add Display="Dynamic" on both of the controls.
<asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator1"
controltovalidate="TextBoxLocation" Display="Dynamic" errormessage="Required"
/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Enter valid Phone number" ControlToValidate="TextBoxLocation" Display="Dynamic" ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" ></asp:RegularExpressionValidator>
Both, simply because one validates client side and the other is server side.
This allows you to make sure the user didn't alter your clientside JavaScript and then send bad data.

is it possible to validate a control in asp.net but not require it?

Is it possible to validate that it's a phone number but not require it? The way it is right now if I don't enter a number it will throw the error. I read somewhere that you can change the RegEx to do this and I tried by enclosing the RegEx in (?:...?)
<asp:TextBox runat="server" ID="tbCompanyFax" Width="99%" Text='<%# Eval("CompanyFax")%>'></asp:TextBox>
<ajaxTK:MaskedEditExtender runat="server" ID="maskCompanyFax" AutoComplete="false" TargetControlID="tbCompanyFax" Mask="(999)999-9999" ClearMaskOnLostFocus="false" />
<asp:RegularExpressionValidator ID="regCompanyFax" runat="server" ControlToValidate="tbCompanyFax" ErrorMessage="Invalid Fax number" ValidationExpression="(?:((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4})?" Display="None"></asp:RegularExpressionValidator>
Your problem arises from the mask being submitted.
You could allow the mask in your RegEx. That would save the trouble of having to write a custom validator.
Try this RegEx
(?:((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4})|(((\(\s{3}\) ?)|(\s{3}-))?\s{3}-\s{4})
Should make an empty mask valid
I tweaked #nunepascal's RegEx and it works exactly as I wanted.
Thanks again!
ValidationExpression="(?:(((\d{3}))|(\d{3}-))?\d{3}-\d{4})|((((_{3}))|(_{3}-‌​))?_{3}-_{4})"

How to use a dynamic character count script on a Textbox that's located in a Detailsview (ASP.NET)

I want to achieve a character counter that displays the number of characters you've typed in a Textbox on my webpage in ASP.NET. This Textbox is nested in a DetailsView.
The normal solution of including (character count script)+(onkeypress for Textbox)+(Readonly input) as listed below wasn't working:
The script:
<script type="text/javascript">
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
else
countfield.value = maxlimit - field.value.length;
}
</script>
The Textbox:
<asp:TextBox ID="TextBox1" runat="server"
onkeyup="textCounter(TextBox1, this.DetailsView.remLen, 300);"
onkeydown="textCounter(TextBox1, this.DetailsView.remLen, 300);"
TextMode="MultiLine" Text='<%# Bind("idea") %>'></asp:TextBox>
And the Input (which is in the DetailsView):
<input readonly="readonly" type="text" name="remLen" value="300" />
Then I found out that having a Textbox nested in a DetailsView screws up the naming convention of the textbox. I tried the C# solution in that link but it couldn't work...
How can I make this work? JQuery seems to be an answer but I have no idea where some code like var Text = $("span[id$=TextBox1]"); would fit into my files. Need help!
I'm working with Microsoft Visual Web Developer 2010 Express in VB (I'm a noob who uses mainly the graphic UI of the program with some programming experience on Android in Java). Wouldn't mind a C# solution if someone had one.
If it is inside of a details view you will probably have to use FindControl. Example:
<asp:TextBox ID="TextBox1" runat="server"
onkeyup="textCounter('<%= ((TextBox)myDetailView.FindControl("TextBox1")).ClientID; %>', this.DetailsView.remLen, 300);"
onkeydown="textCounter('<%= ((TextBox)myDetailView.FindControl("TextBox1")).ClientID; %>', this.DetailsView.remLen, 300);"
TextMode="MultiLine" Text='<%# Bind("idea") %>'></asp:TextBox>
IF you are using ASP.NET 4.0 or later you can set the ClientIDMode property to static.This preserves the id of the control rather than having it renamed by .NET; for example LogoImageButton will be preserved instead of .NET rendering it as ctl00_LogoImageButton. Now your JavaScript can find your control.
DISCLAIMER:
I set ClientIDMode="Static" at the ContentPlaceHolder level to add a counter to a text box so I know it works. BUT according to Rick Strahl (who is a very smart guy) you cannot use an control and specify the ClientIDMode. Like I said though, my implementation works so ...
In any case, I suggest you read Rick's blog on the subject because he covers some important issues relating to inheritance. There are also some interesting comments relating to alternative approaches to accomplishing the same objective. Maybe one of them will work even if you are working with an earlier version of .NET
Rick's blog: http://www.west-wind.com/weblog/posts/2009/Nov/07/ClientIDMode-in-ASPNET-40
You need to use the ClientID property of the text box to get it at runtime in the javascript:
<asp:TextBox ID="TextBox1" runat="server"
onkeyup="textCounter('<%= TextBox1.ClientID %>', this.DetailsView.remLen, 300);"
onkeydown="textCounter('<%= TextBox1.ClientID %>', this.DetailsView.remLen, 300);"
TextMode="MultiLine" Text='<%# Bind("idea") %>'></asp:TextBox>

debug a CompareValidator (ASP.NET)

What is the best way to debug a CompareValidator that always fails the validation? Is there any way to see what the values are that it's comparing to maybe get a clue as to what's going wrong?
Use Firebug to debug the javascript that .Net inserts
If you are not familiar with the other debugging methods, easiest way for you may be utilizing the Response.Write calls to print the values in your button event to see if they are equal to each other:
Response.Write(TextBox1.Text.ToString().Trim());
Response.Write(TextBox2.Text.ToString().Trim());
Response.End();
Update
For simplicity, I will use CompareValidator to check a data type.
You probably have something similar to the following in your ASPX (client side) code:
<asp:TextBox ID="txtTest" runat="server" />
<asp:CompareValidator ID="cvTest" runat="server"
ControlToValidate="txtTest"
Operator="DataTypeCheck" Type="Date"
Display="Dynamic" ErrorMessage="Incorrect format!" />
<asp:Button ID="btnTest" Text="Test Compare Validator"
onclick="btnTest_Click" runat="server" />
In your codebehind (server side), put the following in your btnTest_Click event to see the value that is entered in txtTest:
Response.Write(txtTest.Text.ToString().Trim());
Response.End();
But keep in mind that there more robust debugging utilities that VS offers. This is just a quick-and-dirty way for your purpose.

Regular expression multiline validator

In my ASP.NET Web Form I have a multiline TextBox which should be validated with RegularExpression Validator. Text box should contain one or more strings "a" (just 'a' char, nothing else).
So far I got these regular expressions for my RegularExpressionValidator object:
(?m:(^a$)+)
(?m:\A(^a$)+\Z)
(?m:^a$)
and some others. Neither works. Guess there is something fundamental I'm not getting yet.
Could you please tell me where I'm wrong?
Here's the code involved.
A Button (just for postbacks):
<asp:Button ID="Button1" runat="server" Text="Button" />
The TextBox:
<asp:TextBox ID="TextBox1" runat="server" Rows="10" TextMode="MultiLine"></asp:TextBox>
And the regex validator:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RegularExpressionValidator"
ValidationExpression="(?m:(^a$)+)"></asp:RegularExpressionValidator>
There is nothing else on that Web Form. I've only added those controls and modified properties. I've even did all this using VS GUI.
Using CustomValidator and doing Regex.Match(TextBox1, #"(?m:(^a$)+)") in it works just fine. Something is wrong with RegularExpressionValidator I guess.
If you want to match multiple lines, don't forget to also match the line terminators; they are not implied in $.
(?m:(^a$\r?\n?)+)
might work better.
This matches
a
or
a
a
a
etc.
And, since you're asking for a tutorial, how about regular-expressions.info?

Resources