How to validate years dynamically using validators in ASP.Net? - c#

I have to validate that the year entered must be less than or equals to the current year. I am using server side validators in ASP.Net and C#, and all validators are inside a validator group. So please suggest me to validate one more condition within the same.
Thanks
Amit Ranjan.

Use the ASP.NET CompareValidator.
For e.g. if you have a TextBox with id TextBox1, which accepts a year in 'yyyy' format, then you can do the following:
Year:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator id="CompareValidator1" runat="server"
Operator="LessThan" ControlToValidate="TextBox1" ErrorMessage="Year must
be less than current year" Type="Integer"></asp:CompareValidator>
Add this to code behind:
protected void Page_Load(object sender, EventArgs e)
{
CompareValidator1.ValueToCompare = DateTime.Today.Year;
}
Also remember using validators won't stop a Submit; use these in conjunction with ValidationSummary Control.
More on MSDN: http://msdn.microsoft.com/en-us/library/f9h59855(v=vs.80).aspx

Related

How do I disable dates in asp .net textbox textmode = date?

I'm having this issue where I want to set disable on the dates in the textbox with the textmode = date. I would prefer it to be done in c#.
Any advice?
Here is the aspx page:
<asp:TextBox ID="tbStartDate" runat="server"
AutoPostBack="true" OnTextChanged="tbStartDate_TextChanged"
TextMode="Date"></asp:TextBox>
And the C# file
protected void disablePastDateintextbox()
{
????????
}

Server Side validation not working - ASP.NET

Client side validation works fine. I disabled the client side to see if it also works good server side, but fails. The compiler reaches 'SaveData' even if the input text is invalid.
There are no update panels.
How should I solve this.
ASPX:
<asp:TextBox ID="txtDept" runat="server" pattern="[a-z A-Z]*"></asp:TextBox>
<asp:RegularExpressionValidator
ID="revDept"
runat="server"
ValidationExpression="^[a-zA-Z\s]{1,50}$"
ControlToValidate="txtDept"
Display="Dynamic"
ErrorMessage="Only alphabets and spaces are allowed."
EnableClientScript="false">
</asp:RegularExpressionValidator>
C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SaveData();
}
}
You need to either have "CausesValidation" enabled on the submit button (we can't check in your code if it is so), or to call explicitly "Page.Validate()" before to test the IsValid property.
Please also take a look at How does Page.IsValid work? , it could be helful.

How to find which Image Button has been pressed when using Server Validate

I have a Validate method that looks like this
protected void ValidateHello(Object sender, ServerValidateEventArgs args)
{
//Validate Stuff
}
In my ASP I have this line to validate a drop down list.
<asp:CustomValidator ID="cvNames" runat="server" ControlToValidate="ddlNames" OnServerValidate="ValidateHello" Display="Dynamic" ErrorMessage="Please select a Name">*</asp:CustomValidator>
However I have 2 different imagebuttons. One should have different validation for this drop down box than the other. The only way I can think about doing this is to have an if() statement and check which imagebutton was pressed to cause the validation.
Here is my ImageButton code.
<asp:ImageButton runat="server" ID="imgSearchNames" CssClass="SearchButton" ImageUrl="~/Images/searchbutton.jpg" OnClick="imgSearchNames_OnClick" ></asp:ImageButton>
And this is my OnClick event method.
protected void imgSearchNames_OnClick(Object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
//Do Stuff
}
}
Much help is needed and thanks in advance.
Why don't you use validationGroup.
ValidationGroup property makes your inputs to validate only for particular events( imagebutton_click let's say) ,
<asp:ImageButton ID="imgBtn" ValidationGroup="xxxx" CausesValidation="true" />
<asp:CustomValidator ID="cvNames" runat="server" ValidationGroup="xxxx" OnServerValidate="ValidateHello" Display="Dynamic" ErrorMessage="Please select a Name">*</asp:CustomValidator>
Use same ValidationGroup in your Imagebutton .
You should also consider using ValidateEmptyText=true so that your it will fire validation even for empty controls .

ASP.NET: skip running CompareValidator if some other field is not empty

My search form has 2 fields: Date and Object id. i'm using date validation like this:
<asp:CompareValidator ID="cv" runat="server" Operator="GreaterThanEqual" Type="Date"
ControlToValidate="dateControl" ValueToCompare="" Display="None" SetFocusOnError="False"
ErrorMessage="error msg" EnableClientScript="True"/>
ValueToCompare is set from code-behind (10 days back from now).
i don't want to run date validation, when Object id field is not empty (allows to search without date restrictions). What are solutions without using CustomValidator?
Simply set the 'Enabled' property to false in Code behind file. The Validation is performed after the Page.Load event but just before the event fires for the button or control that triggered the validation.
// Markup portion
<asp:CompareValidator ID="cv" runat="server" Operator="GreaterThanEqual" Type="Date"
ControlToValidate="dateControl" ValueToCompare="" Display="None" SetFocusOnError="False"
ErrorMessage="error msg" EnableClientScript="True"/>
// Code behind file
protected void Page_Load(object sender, EventArgs e)
{
if(!String.IsNullOrEmpty(ObjectId.Text))
{
cv.Enabled=false;
}
}
Now, when the Validation will be performed, CompareValidator will be skipped. You can also set the 'Visible' property to false as a second option. Check the MSDN here.
Check this.may be this help you:
if(!string.IsNullOrEmpty(Objectid.Text))
cv.ValueToCompare=DateTime.Now.AddDays(1);
else
cv.ValueToCompare=DateTime.Now.AddDays(-10);

How to call a private void keypress event handler from client side using C# or ASP.net to allow only numbers into textbox

I've never learned either ASP.net or C# and yet I'm trying to create a textbox using ASP.net that only allows numbers to be entered. I'm using the following code to define my textbox in Default.aspx:
<asp:TextBox runat="server" ID="StudentNo"
autopostback="true"
OnTextChanged="StudentNo_KeyPress"
style="margin-left:20px; width:70px;"/>
The OnTextChanged however isn't calling anything from the server side page (Default.aspx.cs) and here is the code I'm using for that:
using System;
using System.Collections;
...
using System.Data;
using System.Windows.Forms
private void StudentNo_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
}
I've tried to give only the relevant bits with correct indentation but I fear it isn't going to work. I'm sorry if this is a really basic question, but as I said, I've never coded in either of these languages. I'm not allowed to use JavaScript or AJAX, just C# and ASP.net.
Any suggestions or alternative solutions would be fantastic. I've already tried using RangeValidator, RegularExpressionValidator, RequiredFieldValidator and CustomValidator, none of which were any use whatsoever.
Thanks in advance, any help is hugely appreciated. If you require more information, please let me know.
You were headed down the correct path with ASP.NET validation server controls.
Use RegularExpressionValidator this way:
<asp:TextBox id="txtNumber" runat="server" />
<asp:RegularExpressionValidator id="regexValidator" runat="server"
ControlToValidate="txtNumber" ErrorMessage="You must enter a number"
ValidationExpression="^\d+$" />
and if you want to require a number to be entered, then add this one too:
<asp:RequiredFieldValidator id="reqValidator" runat="server"
ControlToValidate="txtNumber" ErrorMessage="You must enter a number" />
Note that the "ControlToValidate" attribute must be set to the control that you are validating. For your example the value would be "StudentNo"

Categories