How to calculate age from date of birth - servlets

I have a user registration form where all user data is stored in database.
I am listing all user data in the UI in a member listing page. In there I have to calculate the age of the user based on their date of birth. I tried by calculating using JSTL, but still I am not getting an answer.
This is what I tried:
<fmt:parseDate value="${user.dateofbirth}" var="parseddate" type="date" pattern="yyyy-MM-dd" />
<jsp:useBean id="now" class="java.util.Date" />
<td class="dataField">
<fmt:formatDate value="${parseddate}" type="date" pattern="MMMM dd yyyy "/>
</td>
<c:set var="today" value="<%=new java.util.Date()%>" />
<fmt:parseNumber type="date" value="${today}" />
<td>
<c:out value="${today-parseddate}"></c:out>
</td>
I am new to JSTL. Can anyone please help me with this?

Here is code that demonstrates how you might do it with JSTL. It is not exactly perfect because I neglected to account for the extra day in a leap year.
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:parseDate value="1979-09-27" var="parsedDate" type="date" pattern="yyyy-MM-dd" />
<jsp:useBean id="now" class="java.util.Date" />
<fmt:parseNumber type="number" integerOnly = "true"
value="${(now.time - parsedDate.time)/(1000 * 60 * 60 * 24 * 365)}" />
Anyway, it outputs 42 years.

If anyone here wants to get the difference between two dates in days and want to display it in another column in the JSP you can you can do like this.
<fmt:parseDate value = "${name_of_your_bean.1st_variable}" var = "formatedDate1" type = "date" pattern = "yyyy-MM-dd" />
<jsp:useBean id="start_date" class="java.util.Date" />
<td > <fmt:formatDate value = "${formatedDate1}" type = "date" pattern = "MMMM dd,yyyy"/> </td>
<fmt:parseDate value = "${name_of_your_bean.2nd_variable}" var = "formatedDate2" type = "date" pattern = "yyyy-MM-dd" />
<jsp:useBean id="end_date" class="java.util.Date" />
<td> <fmt:formatDate value = "${formatedDate2}" type = "date" pattern = "MMMM dd,yyyy"/> </td>
// To display in separate column do like this
<td> <fmt:parseNumber type = "number" integerOnly = "true" value = "${(formatedDate2.time - formatedDate1.time)/(1000 * 60 * 60 * 24)}" /> Days </td>

Related

textbox not accepting digit 10

I have validate a textbox to accept maxsize=2, it accepts 2 digit e.g 11,12... but it does not accepts digit 10
Here is my code
<td width="60" height="20" class="case_txt" align="center">
<input type="text" onblur="CheckUnitValue(this)"
name="Units_<%=cptData.Rows[k]["SERVICEID"] %>"
value="<%=cptData.Rows[k]["NOOFUNITS"] %>"
size="5" maxlength="2" onkeypress="onlyPositiveNumbers(this)" />
</td>
If you are using a modern browser, you can use <input type="number" min="1" max="99"/> as Andy said.
For browsers that doesn't support input type="number" you can correct your script this way.
<html>
<head>
<title>test</title>
<script>
function validateRange(element) {
value = +element.value;
min = element.getAttribute('min');
max = element.getAttribute('max');
if (isNaN(value) || value < min || value > max) {
element.value = '';
}
else
{
element.value = value;
}
}
</script>
</head>
<body>
<input type="number" min="1" max="99" />
<input type="text" maxlength="2" min="1" max="99" onblur="validateRange(this)" />
</body>
</html>
Note:
It's better to use onblure instead on onkeypress, for example when the users pastes a text into field.
I used 2 custom attrinutes min and max on textbox to keep validateRange function more reusable.
It looks like you're overcomplicating simple things.
If you need this textbox accepting only two-digit positive numbers, then you can use type="number" instead of type="text" and set limits for valid values.
Something like this:
<input type="number" min="1" max="99"/>
Pretty simple, and you don't need any custom validation using javascript (I really suppose your onlyPositiveNumbers function has some mistakes as I've stated in comments).

WebForms is not including email input type in form during autopostback

I have an asp:TextBox on a page:
<asp:TextBox ID="edEmail" runat="server" />
And the form is submitted with a normal <asp:Button> control:
<asp:TextBox ID="edEmail" runat="server" />
<asp:Button ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click" />
These are rendered into the client as:
<input name="ctl00$MainContent$edEmail" id="ctl00_MainContent_edEmail"></input>
<input name="ctl00$MainContent$bbOK" id="ctl00_MainContent_bbOK"
type="submit" value="Save User"
onclick='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$bbOK", "", true, "", "", false, false))' >
When the form is submitted through a regular <asp:Button> everything sends correctly. Reading html forms is painful, but the formatted request body is:
&ctl00%24MainContent%24edEmail = asdf%40here.net
&ctl00%24MainContent%24bbOK = Save+User
Excellent, the e-mail address is going to the server. Next we will change the type of the input box to the new html5 email type. We do this after installing the appropriate update to the .NET 4 Framework:
<asp:TextBox ID="edEmail" type="email" runat="server" />
<asp:Button ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click" />
And now we repeat the same procedure. The rendered HTML is:
<input type="email" name="ctl00$MainContent$edEmail" id="ctl00_MainContent_edEmail" >
<input name="ctl00$MainContent$bbOK" id="ctl00_MainContent_bbOK"
type="submit" value="Save User"
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$bbOK", "", true, "", "", false, false))" >
And when we submit the form, the e-mail address form input is present:
&ctl00%24MainContent%24edEmail = asdf%40here.net
&ctl00%24MainContent%24bbOK = Save+User
Excellent, the browser (both IE11 and Chrome 30-something) are submitting the contents of the form as expected.
Next we add something to the page that triggers an "auto-postback", an <asp:RadioGroup>:
<asp:TextBox ID="edEmail" type="email" runat="server" />
<asp:RadioButtonList ID="rbAccountType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="rbAccountType_IndexChanged">
<asp:ListItem>Windows</asp:ListItem>
<asp:ListItem Selected="True">Local</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click" />
This gives the rendered HTML of:
<input type="email" name="ctl00$MainContent$edEmail" id="ctl00_MainContent_edEmail" >
<input id="ctl00_MainContent_rbAccountType_0" type="radio" name="ctl00$MainContent$rbAccountType" value="Windows" checked="checked"><label for="ctl00_MainContent_rbAccountType_0">Windows</label>
<input id="ctl00_MainContent_rbAccountType_1" type="radio" name="ctl00$MainContent$rbAccountType" value="Local"
onclick="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$rbAccountType$1\',\'\')', 0)">
<input name="ctl00$MainContent$bbOK" id="ctl00_MainContent_bbOK"
type="submit" value="Save User"
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$bbOK", "", true, "", "", false, false))" >
But when this form "auto-postsback", the email field is missing:
&ctl00%24MainContent%24rbAccountType = Local&__ASYNCPOST=true&
If i change the email input's type from email to text:
<asp:TextBox ID="edEmail" runat="server" Type="text" />
the rendered radiobutton remains unaffected:
<input id="ctl00_MainContent_rbAccountType_1" type="radio" name="ctl00$MainContent$rbAccountType" value="Local"
onclick="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$rbAccountType$1\',\'\')', 0)">
but the postback data now (correctly) contains exactly what it's supposed to:
&ctl00%24MainContent%24edUsername = ian
&ctl00%24MainContent%24edFullname = Ian%20Boyd
&ctl00%24MainContent%24edDescription = foo
&ctl00%24MainContent%24edEmail = asdf%40here.net
&ctl00%24MainContent%24rbAccountType = Local&__ASYNCPOST=true&
If i change it back to email:
<asp:TextBox ID="edEmail" runat="server" Type="email" />
it again fails, failing to include the email input type
&ctl00%24MainContent%24edUsername = ian
&ctl00%24MainContent%24edFullname = Ian%20Boyd
&ctl00%24MainContent%24edDescription = foo
&ctl00%24MainContent%24rbAccountType = Local&__ASYNCPOST=true&
tldr
WebForms is a buggy architecture that i should have stopped using five years ago There's no fix, and Microsoft won't, so i'm just looking for commiserating. doesn't support HTML 5.
What is WebForms doing that uses the browser to not submit all fields in a form? The failure happens in the IE and Chrome client.
Addendum
The title of this question calls out email input type. But the same bug happens for number input type; and presumably all html5 input types.
And marking up hyper-text in code:
protected void Page_Load(object sender, EventArgs e)
{
edEmail.Attributes["type"] = "email";
edEmployeeID.Attributes["type"] = "number";
...
}
does not solve it. The form still fails to submit its contained values during an "auto-postback" submit (and correctly submitting all values during a "regular" submit).
Impressive that 27 minutes after asking the question, Googling for:
asp.net autopostback not including html5 input types
only gives me as the person experiencing the problem. Apparently i'm the only person trying to shoe-horn HTML5 into WebForms.
Found the bug in the generated WebForms client side Javascript code:
ScriptResource.axd
// Name: MicrosoftAjaxWebForms.debug.js
// Assembly: AjaxControlToolkit
// Version: 3.5.50401.0
// FileVersion: 3.5.50401
// (c) 2010 CodePlex Foundation
_onFormSubmit: function PageRequestManager$_onFormSubmit(evt)
{
var count = form.elements.length;
for (i = 0; i < count; i++)
{
var element = form.elements[i];
var tagName = element.tagName.toUpperCase();
if (tagName === 'INPUT')
{
var type = element.type;
if ((type === 'text') ||
(type === 'password') ||
(type === 'hidden') ||
(((type === 'checkbox') || (type === 'radio')) && element.checked))
{
formBody.append(encodeURIComponent(name));
formBody.append('=');
formBody.append(encodeURIComponent(element.value));
formBody.append('&');
}
}
}
}
By definition, WebForms will not input HTML5 input types in the form body during a postback. It will by definition only support the few original input types:
text
password
hidden
checkbox
radio
color unsupported
date unsupported
datetime unsupported
datetime-local unsupported
email unsupported
month unsupported
number unsupported
range unsupported
search unsupported
tel unsupported
time unsupported
url unsupported
week unsupported
You supposedly need to leave your server control as an <asp:TextBox ... /> but override its type attribute in your code-behind:
edEmail.Attributes["type"] = "email";
[Source]

How to get input text value with a loop if you have txtbox1, txtbox2, txtbox3?

I made a table with input text fields with ids of
<td> <INPUT id="txtName1" type="text" runat="server" /> </td>
<td> <INPUT id="txtDescription1" type="text" runat="server" /> </td>
<td> <INPUT id="txtColNum1" type="text" runat="server" /> </td>
<td> <INPUT id="txtColW1" type="text" runat="server" /> </td>
<td> <INPUT id="txtType1" type="text" runat="server" /> </td>
<td> <INPUT id="txtFormula1" type="text" runat="server" /> </td>
<td> <INPUT id="txtCost1" type="text" runat="server" /> </td>
<td> <INPUT id="txtCostFormula1" type="text" runat="server" /> </td>
<td> <INPUT id="txtPullDown1" type="text" runat="server" /> </td>
<td> <INPUT id="chkLock1" type="checkbox" runat="server" /> </td>
<td> <INPUT id="chkHideQ1" type="checkbox" runat="server" /> </td>
<td> <INPUT id="chkHideW1" type="checkbox" runat="server" /> </td>
and have a javascript to add rows dynamically, incrementing the digit of the id such as
txtName2, txtDescription2, txtColNum2 and so on...
Moreover, I'm saving the data to SQL using vb.net with the code below
Protected Sub btnSaveTemplate_Click(sender As Object, e As EventArgs) Handles btnSaveTemplate.Click
SqlCMData.InsertParameters("categoryName").DefaultValue = txtCategory1.Value
SqlCMData.InsertParameters("productName").DefaultValue = txtName1.Value
SqlCMData.InsertParameters("productDescription").DefaultValue = txtDescription1.Value
SqlCMData.InsertParameters("colNum").DefaultValue = txtColNum1.Value
SqlCMData.InsertParameters("colW").DefaultValue = txtColW1.Value
SqlCMData.InsertParameters("type").DefaultValue = txtType1.Value
SqlCMData.InsertParameters("formula").DefaultValue = txtFormula1.Value
SqlCMData.InsertParameters("cost").DefaultValue = txtCost1.Value
SqlCMData.InsertParameters("costFormula").DefaultValue = txtCostFormula1.Value
SqlCMData.InsertParameters("pullDown").DefaultValue = txtPullDown1.Value
SqlCMData.InsertParameters("lock").DefaultValue = chkLock1.Checked
SqlCMData.InsertParameters("hideQ").DefaultValue = chkHideQ1.Checked
SqlCMData.InsertParameters("hideW").DefaultValue = chkHideW1.Checked
SqlCMData.Insert()
End Sub
My problem is, how can I have a for loop get all the values including the other rows with the id's digit have been incremented such as txtCategory*2*?
Lets say the highest number you get to is 10, you could just have a loop.
Here's and example in quasi-code.
for (i = 1; i < 10; i++)
{
INSERT txtCategory + i;
INSERT txtName + i;
INSERT txtDescription + i;
.
.
.
.
.
.
INSERT chkHideW + i;
}
Obviously the INSERT is just an abbreviation for inserting it to a MySQL table. This should allow you to insert all the elements i times, i being the highest numbered suffix you reached. I can't promise this will work but I hope it helps, at least with the logic behind it.

HTML/ASP.NET: <input type="hidden" name="reference" value="ABC"/>

I just wanna ask if there's a possibility to change:
<input type="hidden" name="reference" value="ABC"/>
into this:
<input type="hidden" name="reference" value="any values I want"/>
where I can set any values behind .cs/C# - making it dynamically. The payment gateway I'm using requires and I can't find a way to included an ASP.NET control ( ?)
and I'm needing your suggestions/comments about it. Thanks.
PS. <asp:HiddenField ID="reference" runat="server" Value="ABC" /> is not working because the payment gateway specifically needs the 'name' property.
I know this is an old post, but for anyone looking to solve this issue now - If you add runat="server" to the input, the name will be changed (e.g. MainContentArea_ctl00_ctl01_ctl01_amount). ClientIdMode="Static" will only help for the ID.
To get around this:
In your html page use a Literal :
<asp:Literal runat="server" ID="litInputAmount"></asp:Literal>
In the code behind file, assign a string to the Text attribute of the Literal This string should be the html as you would like it to be. The correct value can also be added for the value field:
litInputAmount.Text = String.Concat("<input id='inputAmount' type='hidden' name='amount' value='", Price.ToString(), "'>");
This will then be compiled as:
<input id="inputAmount" type="hidden" value="224.4" name="amount">
This will give the information to the payment gateway with the correct name, but your value can be managed dynamically. Repeat for any other values that need to be added before sending.
You can just put runat="server" on the control to access it from your code behind:
<input type="hidden" name="reference" id="reference" runat="server" />
Then, in your code behind:
void Page_Load(object sender, EventArgs e)
{
// ...
reference.Attriutes["value"] = "any values I want";
// ...
}
Note that in this case, the "id" attribute is required because when you have runat="server", the id attribute is used to specify the name of the generated variable.
You can use standard input of type hidden as if you are working with static HTML or Razor, and rely on the <%= expression, which is evaluated at render time rather on DataBind() time as the <%# expressions would.
This way, you can have a normal html, for which you can have ASP.NET WebFroms generate the hidden input's value for you server side, without actually having to mark the input with runat="server" or using <asp:HiddenInput control. See the example below, which should do the job:
<input type="hidden" id="add-to-wishlist-url" value='<%= YourServerSideExpressionHere.Execute() %>' />
Of course, this approach is not one size fits all, but seems like the closest to the meet the requirement described 7 years ago...
//<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
protected string GetVariableValue(string AspxPage, string inputTagName)
{
ra migirad
string RegPattern = string.Format("(?<=({0}\".value.\")).*(?=\"./>)", inputTagName);
Regex regex = new Regex(RegPattern, RegexOptions.IgnoreCase);
Match match = regex.Match(AspxPage);
if (string.IsNullOrEmpty(match.Value))
{
RegPattern = string.Format("<input[^>]*{0}[^>]*value=\"([^\"]*)\"", inputTagName);
regex = new Regex(RegPattern, RegexOptions.IgnoreCase);
match = regex.Match(AspxPage);
return match.Groups[1].Value;
}
return match.Value;
}
Apply the parameter:
ClientIDMode="Static"
For example:
<asp:HiddenField ID="reference" runat="server" Value="ABC" ClientIDMode="Static" />
with this, the "ID" with maintain exactly as "reference".

asp:textbox array

how does one do something like this with asp.net <asp:textbox> and c #? (Thus creating an array of text boxes)
HTML:
<input name="Search[]" value="google" />
<input name="Search[]" value="yahoo" />
<input name="Search[]" value="alltheweb" />
PHP:
$array = $_GET['Search']; // or $_POST['Search'];
/*
$array is now an array like:
array(
0 => "google",
1 => "yahoo".
2 => "alltheweb"
)
/*
Since the controls will all be strongly named it would be easy to just grab them each by name, but if you need them in an array you could wrap the controls in a panel..
You could do something similar to this:
<div runat="server" id="myPanel">
<asp:TextBox runat="server" id="search1" />
<asp:TextBox runat="server" id="search2" />
<asp:TextBox runat="server" id="search3" />
</div>
Linq:
IEnumerable<string> values = myPanel.Controls.OfType<TextBox>()
.Select(textBox => textBox.Text);
Non Linq:
string[] values = new string[myPanel.Controls.Count];
for(int i = 0; i < myPanel.Controls.Count; ++i)
{
values[i] = (myPanel.Controls[i] as TextBox).Text;
}
Edited:
If you are going to dynamically add (or just have non-asp) inputs then it can actually be significantly easier to turn the inputs into an array server side.
For instance if you wish to have a bunch of <input type='text' name='search[]' /> on the page, on the server you can do the following to turn the items into a string array:
string[] inputValues = Request.Form["search[]"].Split(',');
So for the original example provided the equivalent would be:
HTML:
<input name="Search[]" value="google" />
<input name="Search[]" value="yahoo" />
<input name="Search[]" value="alltheweb" />
C#:
string[] myArray = Request.Form["search[]"].Split(',');
/*
myArray is now an array like:
0: "google"
1: "yahoo"
2: "alltheweb"
/*
You could also create the array like this:
TextBox[] textBoxes = new[] { search1, search2, search3 };
<div runat="server" id="myPanel">
<asp:TextBox runat="server" id="search1" />
<asp:TextBox runat="server" id="search2" />
<asp:TextBox runat="server" id="search3" />
</div>
It gives the same end result as Quintin's answer, but I find this easier to read.

Resources