Can I do a warning validate from Datepicker and alert swal like this?
I do that and it error that is_string is not defined.
I'm new in php btw
The comment is a think that i tried to make in different way sorry abort that.
form
<div class="form-group">
<label>Birthdate</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control datepicker_class" id="birth_date" name="birth_date" onchange="validateAge">
</div>
</div>
function
function validateAge(){
var birthday = new $('#birth_date').val();
// let birthday = $('#birth_date').val();
// check = explode('/',birthday);
birthday = explode("/", birthday);
// alert(check);
if (is_string(birthday)) {
birthday = strtotime(birthday);
}
// check
// 31536000 is the number of seconds in a 365 days year. strtotime for 1 years : 31556926
if(time() - birthday < 18 * 31556926) {
swal({
title: "warning",
text: "your age is lower than 18",
type: "warning"
});
}
return true;
}
In javascript there is no is_string() function. To check if variable is string you can do it this way:
if (typeof birthday === 'string' || birthday instanceof String)
//string
else
//not string
Related
I am making a calculator that calculates the age in years but I also want to calculate months Please help me with this Regard Thank you. I want my output like this for 22 years and 3 months. I attach my javascript code and Razor view code. In javascript code, only years are calculated and in Razor view, two text boxes in the first text box take the user's DOB and show his age in the other text box. I want to add a code to calculate months also.DOB is not hardcode .
<html>
<body> <div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth date:</label>
<div class="col-sm-5"> <input asp-for="Dob" id="txtDOB" asp-format="{0:yyyy-MM-dd}" class="form-control" placeholder="YYYY-MM-DD" /> </div>
</div>
\<div class="form-group row"\>
\<label class="control-label col-sm-2" for="Age"\>Age:\</label\>
\<div class="col-sm-5"\>
\<input type="text" id="age" asp-for="Age" class="form-control" /\>
\</div\>
\</div\>
</body>
</html> <script src="~/Scripts/jquery-3.4.1.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#txtDOB").change(function () {
var dob = $("#txtDOB").val();
if (dob == null || dob == "") {
} else {
$("#age").val(getAge(dob));
}
});
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
}
});
</script>
I want when the user to enter the DOB at run time and then the text
box to show the age. In this code, DOB is hard to code.var birth = new
Date("08 Nov 2020 00:00:00 GMT")
Based on your code and comment It seems that you are trying to calculate age what user select in calender and calculate the age autometically along with the month. You can do that both using C# and Javascript. Here is the elegant way to do that using C#, Jquery and Ajax which is more easy and flexible in ragards of formating.
Calculate Age Method:
public object CalculateAge(DateTime dateOfBirth)
{
//DateTime birth = new DateTime(1988, 08, 02);
DateTime birth = dateOfBirth;
DateTime today = DateTime.Now;
TimeSpan span = today - birth;
DateTime age = DateTime.MinValue + span;
// Make adjustment due to MinValue equalling 1/1/1int years = age.Year - 1;
int months = age.Month - 1;
int days = age.Day - 1;
// Print out not only how many years old they are but give months and days as well
var ageInYMD = string.Format("{0} years, {1} months, {2} days", age.Year, months, days);
var ageInYM = string.Format("{0} years, {1} months", age.Year, months);
var ageInY = string.Format("{0} years", age.Year);
return ageInYM;
}
Note: Importantly it will provide you more flexibility to format the date as you want.
Controller:
public IActionResult ViewCalculateAgeJquery() // This is to load view
{
return View();
}
[HttpGet]
public ActionResult CalulateAgeFromDob(DateTime dateOfBirth) // This controller will be called once the age selected.
{
var age = CalculateAge(dateOfBirth);
return Json(age);
}
View:
#model DotNet6MVCWebApp.Models.CalculateAgeModel
<div>
<table class="table table-sm table-bordered table-striped">
<tr>
<th> <label asp-for="DoB"></label></th>
<td> <input asp-for="DoB" id="dateOfBirth" class="form-control" placeholder="Enter date of birth" /><span asp-validation-for="DoB"></span></td>
</tr>
<tr>
<th> <label asp-for="Age"></label></th>
<td> <input asp-for="Age" id="Age" class="form-control" readonly placeholder="Calculated age" /><span asp-validation-for="Age"></span></td>
</tr>
</table>
</div>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$('#dateOfBirth').change(function () {
var dateOfBirth = $('#dateOfBirth').val();
console.log(dateOfBirth);
$.ajax({
url: '/CalculateAge/CalulateAgeFromDob',
type: 'GET',
dataType: 'json',
data: { dateOfBirth: dateOfBirth },
success: function (response) {
console.log(response);
$("#Age").val(response);
alert(response);
},
error: function () {
alert('Error!');
}
});
});
});
</script>
}
Model:
public class CalculateAgeModel
{
public DateTime DoB { get; set; }
public string Age { get; set; }
}
Output:
It will help you to implement as per your requirement.
You can use this to get the difference in months (total months):
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
Use devision (by 12) to get the full years difference, then use modulo to get the remaining months.
var totalMonths = monthDiff(d1, d2);
var years = Math.floor(totalMonths / 12);
var months = totalMonths % 12;
Example fiddle: http://jsfiddle.net/v0dn64rk/
so i'm trying to validate my date input by using a European format so it can be easily inserted into my database. I'm getting an error message pop up trying to tell me to use the required format however after changing the regular expression about a billion times i still can't seem to get it working.
Below is my JS script that is called when i hit the insert button.
function checkForm(form)
{
// regular expression to match required date format
re = /^(\d{4})-(\d{1,2})-(\d{1,2})/>
if(form.startdate.value != '') {
if(regs = form.startdate.value.match(re)) {
// year value between 1902 and 2017
if(regs[1] < 1902 || regs[1] > (new Date()).getFullYear()) {
alert("Invalid value for year: " + regs[1] + " - must be between 1902 and " + (new Date()).getFullYear());
form.startdate.focus();
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
alert("Invalid value for month: " + regs[2]);
form.startdate.focus();
return false;
}
// day value between 1 and 31
if(regs[3] < 1 || regs[3] > 31) {
alert("Invalid value for day: " + regs[3]);
form.startdate.focus();
return false;
}
} else {
alert("Invalid date format: " + form.startdate.value);
form.startdate.focus();
return false;
}
}
}
</script>
This is what calls the insert php file (which deals with the sql side of things) and should called the above JS function. I'm not sure if the error is because i'm also insert a int amount as well as the data within the same submit button.
<form action="insertCarb.php" onsubmit="return checkForm(this)" method="post">
Carb Amount: <input type="text" name="CarbAmount" required/><br>
Date: <input type="text" name="Date" required pattern="/^(\d{4})-(\d{1,2})-(\d{1,2})/" placeholder="yyyy/mm/dd"/><br>
<input type="submit">
</form>
You may change the following code:
<input type="text" name="Date" required pattern="/^(\d{4})-(\d{1,2})-(\d{1,2})/" placeholder="yyyy/mm/dd"/>
To:
<input type="text" name="Date" required pattern="\d{4}-\d{1,2}-\d{1,2}" placeholder="yyyy/mm/dd"/>
I have a form through which I want to accept date only within give date range. But, which ever date I am fetching, it is returning false and showing incorrect range.
Following are the codes related-
register.html-
<div class="form-group row">
<label for="date" class="col-sm-2 col-form-label class='control-label' ">Date of Birth</label>
<div class="col-sm-5">
<input type="date" max="2010-12-31" min="1990-01-01" id="dob" placeholder="Date of birth">
</div>
</div>
controller.js-
var dobInput = document.forms["myform"]["dob"].value;
var maxdate = new Date("2010-12-31");
var mindate= new Date("1990-01-01");
if(maxdate>dobInput && dobInput>mindate)
{
alert("correct range");
}
else{
alert("Input out of range");
return false;
}
The Value you're getting is returned as a string, however you're attempting to evaluate this against Date type variables - this will not work as a string to string evaluation will be done lexicographically.
You should instead convert the value to a date first:
var inputDate = new Date(dobInput);
if(maxdate>inputDate && inputDate >mindate){
...
Your input is a string. so convert to Date first and check with getTime method. Correct code is as below..
var dobInput = document.forms["myform"]["dob"].value;
var maxdate = new Date("2010-12-31");
var mindate= new Date("1990-01-01");
var dateToChk = new Date(dobInput);
if(maxdate.getTime()>dobInput.getTime() && dobInput.getTime()>mindate.getTime())
{
alert("correct range");
}
else{
alert("Input out of range");
return false;
}
I have a form that uses jQuery validate, but the form is generated dynamically and I am trying to add an additional method for validating whether a date is before another, if that date has been used before.
The HTML is the following (with the names generated dynamically):
<div class="form-group">
<label class="control-label col-md-2">Read Date</label>
<div class="input-group col-md-4 date date-picker" data-date-format="dd/mm/yyyy">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" class="form-control insert-val" readonly="" name="datepicker_16" aria-required="true" aria-invalid="false">
</div>
<span class="help-block">Enter the date of the reading</span>
<span class="input-group-btn">
<button class="btn default" type="button" style="margin-top: -18px;"><i class="fa fa-calendar"></i></button>
</span>
</div>
<input type="hidden" name="prevdate_16" class="form-control prev-date" value="29/05/2015">
With the following jQuery to validate the date field:
$('#readingForm .insert-val').each(function(){
var prevDate = $(this).parents('.form-group').find('.prev-date').val();
var useLTD = true;
if(prevDate !== ''){
$.validator.addMethod("less_than_date", function(value, element) {
var curDate = value;
var curarr = curDate.split('/');
var curDay = curarr[0];
var curMonth = curarr[1];
var curYear = curarr[2];
var ncurDate = new Date();
ncurDate.setFullYear(curYear, curMonth-1, curDay);
var prevarr = prevDate.split('/');
var prevDay = prevarr[0];
var prevMonth = prevarr[1];
var prevYear = prevarr[2];
var nprevDate = new Date();
nprevDate.setFullYear(prevYear, prevMonth-1, prevDay);
return ncurDate <= nprevDate;
}, "The reading date must be greater than the previous reading date.");
} else {
useLTD = false;
}
$(this).rules( "add", {
required: true,
minlength: 10,
dateITA: true,
less_than_date: useLTD
});
});
Before the I added the "add method", it correctly validated the date, but now it does not, and doesnt accept even if the date is greater than the previous date.
Really stumped on this one, any help would be greatly appreciated.
Ok, as soon as I posted this, I realised that the return was the wrong way round.
Should have been:
return nprevDate <= ncurDate;
[I have updated this question below, please see new question on infinite looping of alert]
I have a date of birth field in my form and there is an input field as well as date picker.
After keying in the correct value, the change function is activated and runs the logic as below to do some processing to the date of birth to get age.
However, when I use alert() to prompt for the value of the date of birth, I am not able to see the value I keyed in reflected, instead, it is showing an empty string.
I tried document.getElementById("9_element14").value, but that didn't work, it showed undefined. So I switched to jQuery and now it shows empty string.
It is a Wordpress form maker form, so there is restriction in amending the HTML, but I can change the JavaScript.
Any advice is much appreciated.
The link to the form is here:
http://lionfish.vodien.com/~scforgsg/RC7/menu-parent-courses/course-application/
My codes are as below:
HTML
<tr id="9" type="type_date"><td valign="middle" align="left" id="9_label_section14" class="">
<span id="9_element_label14" class="label">Date of Birth:</span>
<span id="9_required_element14" class="required"> *</span></td>
<td valign="middle" align="left" id="9_element_section14" class=" toolbar_padding"><input type="hidden" value="type_date" name="9_type14" id="9_type14">
<input type="hidden" value="yes" name="9_required14" id="9_required14">
<input type="text" value="" class="wdform_date" id="9_element14" name="9_element14" maxlength="10" size="10" onchange="change_value('9_element14')">
<input id="9_button14" type="reset" value="..." format="%d-%m-%Y" onclick="return showCalendar('9_element14' ,'%d-%m-%Y')" class="button">
</td>
</tr>
JAVASCRIPT
// before form is load
function before_load()
{
}
$(document).ready(function() {
$('[id$=11]').hide();
$('[id$=49]').hide();
});
// before form submit
function before_submit()
{
}
// before form reset
function before_reset()
{
}
function on_choose_course() {
var course = document.getElementById("1_element14");
var selected = course.options[course.options.selectedIndex].value;
if (selected=="Canoe Polo Lvl 1" || selected=="Kayaking Orientation" || selected=="1 Star Award"){
$('[id$=49]').hide();
}
else{
$('[id$=49]').show();
}
}
$(function(){
$('[id$=9_element14]').change(function(e) {
on_date_select();
});
});
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/);
return dtRegex.test(dtValue);
}
function on_date_select() {
//calculate age
var current_year = new Date().getFullYear();
if ($('[id$=9_element14]').length) {
var dob = $('[id$=9_element14]').val();
alert($('[id$=9_element14]').val());
if (ValidateDate(dob)){
var age = current_year - substr(dob, 6, 10);
alert(substr(dob, 6, 10));
alert(age);
if (age<21){
//show declaration is 21 and above
$('[id$=11]').show();
}
if (age>=21){
//show declaration is 21 and above
$('[id$=11]').hide();
}
}//end validatedate
}//end check empty
}
==================================================================
Thanks guys for helping! Using jsfiddle and making changes here and there, I derived the conclusion that the way I was using substring for dob was not working, causing the whole function to fail.
So now I have corrected it. Only problem now is that I am getting an infinite looping of alerts when date of birth is invalid.
NEW CODES:
// before form is load
function before_load()
{
}
$(document).ready(function() {
$('[id$=11]').hide();
$('[id$=49]').hide();
});
// before form submit
function before_submit()
{
checkDetails($('[id$=15_element140]'),$('[id$=21_element14]'));
}
// before form reset
function before_reset()
{
}
function on_choose_course() {
var course = document.getElementById("1_element14");
var selected = course.options[course.options.selectedIndex].value;
if (selected=="Canoe Polo Lvl 1" || selected=="Kayaking Orientation" || selected=="1 Star Award"){
$('[id$=49]').hide();
}
else{
$('[id$=49]').show();
}
}
function checkDetails(e,f){
if (e.checked && (f.trim()).length==0){
alert("Please give details about the medical condition.");
e.focus();
}
}
$(function(){
$('[id$=9_element14]').change(function(e) {
on_date_select();
});
});
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/);
return dtRegex.test(dtValue);
}
function on_date_select() {
//calculate age
var current_year = new Date().getFullYear();
if ($('[id$=9_element14]').length) {
var dob = $('[id$=9_element14]').val();
if (ValidateDate(dob)){
var age = current_year - dob.substring(6, 10);
if (age<21){
//show declaration is 21 and above
$('[id$=11]').show();
}
if (age>=21){
//show declaration is 21 and above
$('[id$=11]').hide();
}
}else{
$('[id$=9_element14]').focus(
function() {
alert("Date of Birth is invalid");
}
);
}//end validatedate
}//end check empty
}
The ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Change your element identificators according the rules and everything will work.
More information here and here.