I am using compare validator of asp.net to compare the Date, I am comparing input date with today's date for that I have written code as below.
<asp:CompareValidator ID="StartDateCompareVal" ValidationGroup="vgStep4" runat="server"
ControlToValidate="txtDueDate" Display="Dynamic" ErrorMessage="Dateshould be greater than today's date."
Operator="GreaterThan" ValueToCompare="<%# DateTime.Today.ToShortDateString() %>"
Type="Date"></asp:CompareValidator>
It is working fine, but Now my requirement is that if someone enters date as 00/00/0000 so, No need to compare the value and should be accepted
Looks like you might want to use a CustomValidator instead of the CompareValidator.
.aspx page:
<form id="frmAspnet" runat="server">
<asp:ValidationSummary runat="server" ID="vSummary" />
<div>
<label>
Enter Date Greater Than Today:
<asp:TextBox runat="server" ID="txtDate" />
</label>
</div>
<div>
<asp:Button runat="server" ID="cmdSubmit" Text="Submit" />
</div>
</form>
code behind:
private void cmdSubmit_Click(object sender, EventArgs e)
{
String validationGroup = "vgStep4";
vSummary.ValidationGroup = validationGroup;
Page.Validate(validationGroup);
DateTime dateEntered = DateTime.TryParse(txtDate.Text, out dateEntered) ? dateEntered : DateTime.MinValue;
Page.Validators.Add(new CustomValidator()
{
IsValid = (dateEntered > DateTime.Now.Date) || (txtDate.Text == "00/00/0000"),
ValidationGroup = validationGroup,
ErrorMessage = "Date should be greater than today's date."
});
if (Page.IsValid)
{
// Date entered is valid!
// or 00/00/0000 was entered
}
}
Related
Requirement is simple.
How to set current date in CalendarExtender control.
<cal:CalendarExtender ID="calDate" runat="server" SelectedDate="2008-01-01" TargetControlID="txtDate" CssClass="CalendarExtender" Format="yyyy/MM/dd">
Here the selected date is 2008-01-01. I need to show current date instead of 2008-01-01
Appreciate your assistance
You just need to assign it in codebehind, for example in Page_Load:
if(!IsPostBack)
calDate.SelectedDate = DateTime.Today;
Another example using #Hutchonoid approach: example below illustrate how to correctly use ajaxcontrolTookKit CalendarExtender.
<ajaxControlToolKit:CalendarExtender runat="server"
id="cal1"
TargetControlID="txtDateFrom"
CssClass="MyCalendar ajax__calendar ajax__calendar_hover"
Format="dd/MM/yyyy"
PopupButtonID="imgControl"
PopupPosition="BottomRight"
SelectedDate="<%# DateTime.Today %>" >
</ajaxControlToolKit:CalendarExtender>
<asp:TextBox Type="text" ID="txtDateFrom" runat="server"></asp:TextBox>
<asp:ImageButton ID="imgControl" runat ="server" ImageUrl
="~/_icons/ajaxcalendar.png" />
Hope the above code snip-it helps or at least clarify the concept.
I am using a range validation in asp for a date range...
<EditItemTemplate>
<asp:RequiredFieldValidator ID="RequiredFieldValidatordtmStartDateEdit" runat="server" ErrorMessage="Start Date is required" ControlToValidate="dtmStartDateEdit"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidatordtmStartDateEdit" runat="server" Type="String" ErrorMessage="Range is +/- 1 year" ControlToValidate="dtmStartDateEdit" MaximumValue="DATETIME.Today.ADDYEARS(1).ToShortDateString()" MinimumValue="DATETIME.Today.ADDYEARS(-1).ToShortDateString()"></asp:RangeValidator>
<ajaxToolkit:CalendarExtender ID="CalendarExtenderStartDateEdit" runat="server" TargetControlID="dtmStartDateEdit"></ajaxToolkit:CalendarExtender>
<asp:TextBox ID="dtmStartDateEdit" runat="server">
</asp:TextBox>
</EditItemTemplate>
The error I get is that the Maximum cannot be smaller than the minimum.
Add type attribute , and I wonder ToShortDateString() returns String or use Type = Date if not.
<asp:RangeValidator ID="RangeValidatordtmCloseDateAdd" runat="server"
ErrorMessage="Range is +/- 1 year" ControlToValidate="dtmCloseDateAdd"
MaximumValue="DATETIME.Today.ADDYEARS(1).ToShortDateString()"
MinimumValue="DATETIME.Today.ADDYEARS(-1).ToShortDateString()"
Type = "String">
</asp:RangeValidator>
What I did was extract the Max and Min statements and placed them in the PageLoad event for each RangeValidator. It works fine.
I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?
Set AutoPostBack= true for the first ddl
U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}
I have followed this wiki and have successfully built a custom query.
It works fine. I have used a join between tables.
My question is how do I display it on a jsp using liferay search container since className in search container requires one model class.
EDIT:
What I have tried till now is this:
<%
getAttendanceData attName = new getAttendanceData();
List<Object[]> displayAttListName = AttendanceLocalServiceUtil.findAttendance();
ArrayList name = new ArrayList();
ArrayList title = new ArrayList();
ArrayList status = new ArrayList();
ArrayList remarks = new ArrayList();
for(Object[] att:displayAttListName) {
name.add(att[0]);
title.add(att[1]);
status.add(att[2]);
remarks.add(att[3]);
}
%>
<liferay-ui:search-container delta="20" emptyResultsMessage="No Results Found">
<liferay-ui:search-container-results
total="<%= displayAttListName.size() %>"
results="<%= ListUtil.subList(displayAttListName , searchContainer.getStart(), searchContainer.getEnd()) %>"
/>
<liferay-ui:search-container-row modelVar="search"
className="java.lang.Object">
<%
for(Object displayName:name) {
%>
<liferay-ui:search-container-column-text name='studName' value = '<%=String.valueOf(displayName)%>' href="">
</liferay-ui:search-container-column-text>
<%
}
%>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator/>
</liferay-ui:search-container>
What I have done above displays each of the 10 names 10 times in a column.
I want the names to appear on each new row. How shoould I modify the above code?
EDIT 2
Considering the name array defines earlier I did the following:
<liferay-ui:search-container-column-text name="employee name" href = "">
<%=name.getClass().getDeclaredFields().toString() %>
</liferay-ui:search-container-column-text>
With the above, I am getting the result something like: [Ljava.lang.reflect.Field;#195f1af on each row.
I see that the name, title, status and remarks field are all String (as per your comment) so in the for loop you should cast the Object as a String and you don't need the four ArrayList for this.
Here is how the row tag would look like:
<liferay-ui:search-container-row className="java.lang.Object" modelVar="search">
<%--
Since an "Object[]" is nothing but an "Object", we first cast the "search"
instance to an "Object[]" and then to a "String"
--%>
<liferay-ui:search-container-column-text name='name' value='<%= (String) ((Object[])search)[0] %>' />
<liferay-ui:search-container-column-text name='title' value='<%= (String) ((Object[])search)[1] %>' />
<liferay-ui:search-container-column-text name='status' value='<%= (String) ((Object[])search)[2] %>' />
<liferay-ui:search-container-column-text name='remarks' value='<%= (String) ((Object[])search)[3] %>' />
</liferay-ui:search-container-row>
There you go, this should work.
A more cleaner way I think would be to have a POJO defined that would store these values and then the POJO's list can be returned. I have not tried the second approach though.
Another standard approach is to include extra fields in any one of the entity's *Impl and then returning the list of that entity, in your case I would assume you have Student and Attendance entities, so you can put the fields status & remarks in StudentImpl and then return a List<Student> or put fname in AttendanceImpl and return List<Attendance> from the finder method. (updated after this comment)
I have a text box using cc1:Editor and when I place a required field validator on it, it displays as soon as the page loads. How can I hide the error and allow it to display only if the html editor box is empty?
<code><cc1:Editor ID="txtDescription" Width="500px" Height="525px"
runat="server" TextMode="SingleLine" /></code>
<code>
<asp:RequiredFieldValidator ID="rfvDescription" runat="server"
ControlToValidate="txtDescription"
ErrorMessage="Must include Description" Font-Bold="True"></asp:RequiredFieldValidator>
</code>
<code><asp:Button ID="SubmitBtn" runat="server"
Text="Submit" OnClick="SubmitBtn_Click" class="form-td" Height="30px" />
<script language="javascript" type="text/javascript">
document.onkeypress = keyhandler;
function keyhandler(e) {
Key = window.event.keyCode; if (Key == 13) {
var obj = document.getElementById('<%=SubmitBtn.ClientID%>');
obj.focus();
obj.click();
}
}
</script>
Yes, you can perform custom validation on your submit button client side & server side validation on your postback event thus removing required field validator. Check following example:
On your aspx page
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:return ValidateEditor();"
ValidationGroup="myGroup" onclick="Button1_Click" />
<br />
</p>
<asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
<cc1:Editor ID="Editor1" runat="server" />
<script type="text/javascript">
function ValidateEditor() {
var txtEditor = $find('<%=Editor1.ClientID %>');
if (txtEditor.get_content() == null || txtEditor.get_content() == '') {
alert('Text cannot be empty');
document.getElementById('<%=lblMessage.ClientID %>').innerHTML='Text cannot be empty';
return false;
}
else
return true;
}
</script>
On server side
if (string.IsNullOrEmpty(Editor1.Content.ToString()))
{
lblMessage.Text = "Text cannot be empty";
}
else
{
// Do your work here
}