Javascript date validation not working - javascript

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"/>

Related

Converting HTML form input into Javascript variables and comparing values

I am trying to compare the birth dates of two people. Person 1 and Person 2 input their names and dates of birth in an HTML form, and I want to use Javascript to compare the two dates and print out which person is older on the HTML page. However, I'm not sure how to submit the form and compare the dates. Here is what I have so far for the HTML:
<form id="form1">
Full name of first person: <input type="text" name="name1"><br>
Birthday: <input type="date" date="date1"><br>
<br>
Full name of second person: <input type="text" name="name2"><br>
Birthday: <input type="date" date="date2"><br>
</form>
And the Javascript:
var name1 = document.getElementsByName("name1");
var name2 = document.getElementsByName("name2");
var date1 = document.getElementsByName("date1");
var date2 = document.getElementsByName("date2");
How do I submit the variables in HTML and then have Javascript compare the two dates?
You forgot two things:
A submit button.
A submit handler.
I guess this solves your question.
window.onload = function () {
document.getElementById("form1").onsubmit = function () {
var name1 = document.getElementById("name1");
var name2 = document.getElementById("name2");
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
if ((new Date(date1.value)).getTime() < (new Date(date2.value)).getTime()){
console.log(name1.value + " is greater than " + name2.value)}
else if ((new Date(date1.value)).getTime() > (new Date(date2.value)).getTime()){
console.log(name2.value + " is greater than " + name1.value)}
else{
console.log(name2.value + " and " + name1.value + " are of same age.")};
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
<input type="submit" value="Check" />
</form>
You need to add an action to the form and a submit button. Then you can add an onsubmit call from your button to invoke a simple string comparison function to see which number is greater
Basic form data access demo
var compare = function () {
var form = document.getElementById("form1");
var output = document.getElementById("demo");
output.innerHTML = "";
for(var i = 0; i< form.length; i++){
output.innerHTML = output.innerHTML +" "+ form.elements[i].value;
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
</form>
<input type="button" name="submit" value="Compare " onclick="compare()" />
<p id="demo"></p>
Well, let's go step by step on this
1. How to submit a form
In HTML you have 2 ways of submitting a form:
Through an <input> tag with the type="submit" attribute (resulting in <input type="submit" />
Trough a <button> tag with the type="submit" attribute (resulting in <button type="submit">...content...</button>
Now when these buttons get clicked, they will trigger the <form>'s submit event.
2. How to subscribe to a form's submit event
As when submitting a form, there're (without any external libraries) 2 ways of subscribing to a form's submit event:
Directly setting a property on the form: formvar.onsubmit = function() { /* ... do stuff ... */ } (not really recommended as other plugins/scripts might overwrite this)
Adding an event listener: formvar.addEventListener("submit", function() { /* ... do stuff ... */ } (better than directly setting a property as this won't be removed when another script subscribes to the same event)
3. Comparing dates
Well, first you'd have to transform the dates from the string value you got from the textbox to a proper Date type:
date1 = Date.parse(date1.value);
date2 = Date.parse(date2.value);
And then with a simple arithmetic operator you can find out which one of them is the oldest:
var difference = date2 - date1;
if(difference > 0)
{
// Second person is the oldest
}
else if (difference < 0)
{
// First person is the oldest
}
else
{
// They are the same age
}
You don't need to submit the form to check the difference. A simple onclick function or click event listener will do.
You need to check if they are older, younger, or the same age. Try it below. You code wasn't working because you didn't have a name property for your dates. I switched them to use ids.
document.getElementById("theButton").addEventListener('click', checkOldest);
function checkOldest() {
var name1Value = document.getElementById("name1").value,
name2Value = document.getElementById("name2").value,
date1Value = document.getElementById("date1").value,
date2Value = document.getElementById("date2").value,
result = document.getElementById("result");
// make sure you have input for both birthdates and names
if (name1Value && name2Value && date1Value && date2Value) {
var dateOneComparedToTwo = new Date(date1Value) - new Date(date2Value);
if (dateOneComparedToTwo < 0) {
result.innerText = name1Value + ' is older than ' + name2Value + '!';
} else if (dateOneComparedToTwo > 0) {
result.innerText = name1Value + ' is younger than ' + name2Value + '!';
} else {
result.innerText = name1Value + ' and ' + name2Value + ' are the same age!';
}
} else {
result.innerText = "You need to fill out the form completely!";
}
}
<form id="form1">
Full name of first person: <input type="text" id="name1" name="name1"><br>
Birthday: <input type="date" id="date1" name="date1"><br>
<br>
Full name of second person: <input type="text" id="name2" name="name2"><br>
Birthday: <input type="date" id="date2" name="date2"><br>
<button id="theButton">Who's oldest?</button>
</form>
<p id="result">
Fill out the form please!
</p>

Validate date with jquery and help user

I make a jQuery function which should check user value. The date format what I need is "YYYY-MM-DD". I want to insert "-" in the users text when the length is 5 and 8. What I make:
$(document).ready(function(){
$('input[type=date]').keydown(function(){
var leng = $(this).val().length;
var content = $(this).val();
if(leng == 5){
$(this).text(content+"-");
}else if(leng == 8){
$(this).text(content+"-");
}
});
});
<input type="date" name="openDatePerm1" class="form-control"
id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
It isn't insert "-" when it should (it do it never). What I do wrong?
You should use $(this).val(content+"-");
You just need to assign by using $(this).val(..), and not $(this).text(..), then just shift your variables by one, so (leng == 4) rather than (leng == 5) and (leng == 7) rather than (leng == 8)
$(document).ready(function(){
$('input[type=date]').keydown(function(){
var leng = $(this).val().length;
console.log(leng)
var content = $(this).val();
if(leng == 4){
$(this).val(content+"-");
}else if(leng == 7){
$(this).val(content+"-");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
Your solution almost got it right, here a small tweak to yours.
1- the correct function to use is $(this).val(content+"-"); using the function val() not text() as in your example: $(this).text(content+"-");
2- users might need to delete/erase using backspace, then there should be an exception for it. Otherwise the function will keep re-adding the previous content and the user won't be able to delete his input.
3- the number of chars are: 4 and 7 not 5 and 8. Because the first '-' should be inserted after exactly 4 digits e.g. 1999 then '-'. After that the month which is two digits added to the year plus one hyphen 4+1+2 is 7 digits in total.
Here is a working solution:
DEMO
$(document).ready(function() {
$('input[type=date]').keydown(function() {
//Capture the field object
$field = $(this);
//Verify if the user is trying to delete or add new chars
$('html').keyup(function(e) {
if (e.keyCode == 8) {} else {
//alert("here");
//Call the function that will count the chars and add '-'
addDash($field);
}
});
});
function addDash($field) {
var leng = $field.val().length;
var content = $field.val();
if (leng == 4) {
$field.val(content + "-");
} else if (leng == 7) {
$field.val(content + "-");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
make a jQuery function which should check user value. The date format
what I need is "YYYY-MM-DD"
It is not necessary to insert "-" at input type="date" value . If this.checkValidity() returns true , input value should be valid , including "-" between each YYYY , MM , DD . To view resulting string use this.value , to view value as Date string use this.valueAsDate . To make certain that each YYYY , MM , DD are set , try also setting minlength attribute to 10
$(document).ready(function(){
$("input[type=date]").change(function() {
console.log(this.checkValidity(), this.value, this.valueAsDate)
});
});
input[type="date"]:invalid ~ label[for="input"]:after {
color:red;
content:"Invalid date ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10"><br>
<label for="input"></label>
Alternatively, using pattern attribute with RegExp
(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))
See HTML5 Pattern - Dates
$(document).ready(function() {
$("input[type=text]").change(function() {
console.log(this.checkValidity(), this.value, this.valueAsDate)
});
});
input[type="text"]:invalid ~ label[for="input"]:after {
color: red;
content: "Invalid date. Required date format: YYYY-MM-DD ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))">
<br>
<label for="input"></label>

All Browsers seem to ignore JavaScript Client Side form validation rule

I've used JavaScript to ensure that the fields on my form are correctly filled out (required fields with correct type of information) and the browser seems to ignore the rules I set and process the information anyway.
HTML
HTML
<form id="course-form" name="courseForm" method="POST" onSubmit="return checkCourse()" action="#">
<label for="courseName">Course Name: </label>
<input type="text" id="course-name" name="courseName" placeholder="Course Name" required/><br/>
<br>
<label for="qualDesc">Description: </label><br/>
<textarea name="qualDesc" class="boxsizingBorder" placehold
<label for="entryReqs">Entry Requirements</label><br>
<textarea name="entryReqs" class="boxsizingBorder" id="entry-reqs" placeholder="Previous Grades Required" required></textarea><br>
<br>
<label for="cost">Cost: £</label>
<input type="text" name="cost" id="courseCost" maxlength="6" size="5" required/><br>
<br>
<input type="submit" value="Add Course" />
</form>
JavaScript(Placed in Head of document)
<script>
function checkCourse()
{
var date = new Date();
var year = (date.getFullYear());
var courseName=document.forms["courseForm"]["courseName"].value;
var courseDesc=document.forms["courseForm"]["qualDesc"].value;
var courseYear=document.forms["courseForm"]["year"].value;
var entryReqs=document.forms["courseForm"]["entryReqs"].value;
var cost=document.forms["courseForm"]["cost"].value;
if(courseName == "")
{
alert("Course name is a required field.");
return false;
}
else if(courseDesc=="")
{
alert("The Course needs a description");
return false;
}
else if(courseYear < year)
{
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);
return false;
}
else if(entryReqs=="")
{
alert("You must enter some entry requirements");
return false;
}
else if(isNaN(cost) || (cost==""))
{
alert("Cost is not a valid numerical figure");
}
alert("Course added sucessfully!");
return true;
}
</script>
**Note, I've also tried putting the return true section in an else statement like this:
else
{
alert("Course added sucessfully!");
return true;
}
Am I missing something?
Thanks
In the line below, you try to get the value of an input, but your form does not contain an input that is named year. This will cause a Javascript error and subsequently, your validation will be disregarded and the form will continue to submit
var courseYear=document.forms["courseForm"]["year"].value;
A second problem is you don't return false if the cost validation fails (but this is not your root problem).
Also as juvian points out, you are missing a closing quote on the alert below:
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);

jquery Datepicker date range validation

I have a field like Born date. I have used jquery datepicker to show the calender so that user can select the date.Now I have a problem.
In the the Born date field there is a option to choose between which opens two date picker fields like
Born Date -- Between--------- ---From------- And --To----------
Now the problem is if the user selects a date in 'To field' which is less than 'From field' and press the submit button it gets submitted. I need to prevent it from submitting and display appropriate message so the user enters right date .
Please Help.
Here is the code that i am using
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</input>
<span id="span_borndate" style="display:none">
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</span>
This is the Java script i am using
function checkdate(fieldname) {
var comparator = '#comp_' + fieldName;
var compVal = $(comparator).val();
Value = $('#' + fieldName).val();
var fromDate = jQuery.datepicker.parseDate('mm-dd-yy', Value, null);
Values = $('#' + fieldName + '-to').val();
var toDate = jQuery.datepicker.parseDate('mm-dd-yy', Values, null);
$('#span_' + fieldName).find('.error').remove();
if (compVal == "Between") {
if (toDate < fromDate) {
$('#span_' + fieldName).append("<label class='rangeError' generated='false'>Start date should come before end date</label>");
return false;
}
}
return true;
}
And this is the function which is called again while submitting
function validateforms() {
var valid = true;
$('//classnamefor table rows which includes the date td').each(function (index) {
fieldName = $(this).attr("name");
if ($('#' + fieldName).hasClass('dateISO')) {
valid = checkDate(fieldName);
}
}
return valid;
}
Try this
http://jqueryui.com/demos/datepicker/#date-range
and make the textboxes readonly='true'
<input type="text" id="from" name="from_date" value="" readonly="true"/>
<input type="text" id="to" name="to_date" value="" readonly="true"/>

How can I validate multiple different form fields, I have searched and searched for a week

How do I validate dd/mm/yyyy, numeric loan amount, alphabetic first, last name together. I am having trouble using this forum. Thanks for responding so fast!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
<!--//
function validate(form){
var message = 'Please fill in the following fields:\n\n\t';
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length == 0){
message+= form.elements[i].name.toUpperCase()+'\n\t';
}
}
message+= '\nOK submit incomplete form';
message+= '\nCANCEL return to the form';
message = confirm(message);
if(!message){ return false };
else{ return true };
}
//-->
</script>
</head>
<body>
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name: <input type="text" name="firstname" maxlength="15"><br>
Last Name: <input type="text" name="lastname" maxlength="15"><br>
Birth Date: <input type="text" name="birthdate" maxlength="8"><br>
Loan Amount: <input type="text" name="loanamount" maxlength="6" ><br>
Years: <input type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
</body>
</html>
You can use a function like this. It sets up a regular expression for each type of field and then makes a table that says which regular expression to use for which form element. It uses the named form elements to access the individual values.
function validate(form) {
var nameRE = /^[A-Za-z \.]+$/;
var dateRE = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var amountRE = /^\$?[\d\.,]+$/;
var yearsRE = /^\d+$/;
var formItems = [
{name: "firstname", re: nameRE, tag: "First Name"},
{name: "lastname", re: nameRE, tag: "Last Name"},
{name: "birthdate", re: dateRE, tag: "Birth Date", isDate: true},
{name: "loanamount", re: amountRE, tag: "Loan Amount", min: 50000, max: 750000},
{name: "years", re: yearsRE, tag: "Years", min: 5, max: 30}
];
var item, val, num, month, day, year, valid, matches, incomplete = false;
var msg = 'Please fill in the following fields:\n\n\t';
for (var i = 0; i < formItems.length; i++) {
item = formItems[i];
// strip leading or trailing whitespace
var val = form[item.name].value.replace(/^\s+|\s+$/g, "");
form[item.name].value = val;
// see if it matches the regex
valid = item.re.test(val);
if (valid && item.isDate) {
matches = val.match(item.re);
month = parseInt(matches[1], 10);
day = parseInt(matches[2], 10);
year = parseInt(matches[3], 10);
if (month <= 0 || month > 12 ||
day <= 0 || day >= 31 ||
year < 1900 || year > 2020) {
valid = false;
}
}
if (!valid) {
incomplete = true;
msg += item.tag + '\n\t';
} else {
if (item.min && item.max) {
// clear out non-numeric chars
val = val.replace(/[,\$\s]/g, "");
// convert to a number
num = parseInt(val, 10);
// compare to min and max
if (num < item.min || num > item.max) {
incomplete = true;
msg += item.tag + " (must be between " + item.min + " and " + item.max + ")\n\t";
}
}
}
}
if (incomplete) {
msg += '\nOK submit incomplete form';
msg += '\nCANCEL return to the form';
return(confirm(msg));
}
return(true);
}
​
Working demo here: http://jsfiddle.net/jfriend00/GChEP/
A way to do would be to use classes to know what kind of validation you need for a given input. Also, you can use the title attribute to have a more human-friendly representiation of the input.
Your HTML would then look like:
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name (text only): <input class="validate-text" title="First Name" type="text" name="firstname" maxlength="15"><br>
Last Name (text only): <input class="validate-text" title="Last Name" type="text" name="lastname" maxlength="15"><br>
Birth Date (format dd/mm/yyyy): <input class="validate-date" title="Birth Date" type="text" name="birthdate" maxlength="8"><br>
Loan Amount (US dollars, numeric only): <input class="validate-number" title="Loan Amount" type="text" name="loanamount" maxlength="6" ><br>
Years (numeric only): <input class="validate-number" title="Years" type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
And your JavaScript function (regular expressions seem to be the best way to go):
function validate(f) {
var message=new Array(); //will contain the fields that are misfilled
var reText=new RegExp("^[a-z \-'\.]+$", "i"); //a RegExp to match names: only letters, "-", "'" and "." allowed
var reDate=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"); //a RegExp to match a date in the format dd/mm/yyyy
var reNumber=new RegExp("^[0-9]+$"); //a RegExp to match a number
for(var e in f.elements) { //loop on every input of the form
var test=null; //set or reset the RegExp to use for the current input
var input=f.elements[e]; //assign the input to a var (easier to type, not needed)
if(!input.className) //if this input doesn't have any class declared
continue; //then we skip the rest of the loop to keep going with the next input
var classes=input.className.split(" "); //maybe the input has several classes, so we split them in a "classes" array
for(var c in classes) { //we loop on every class of the current input
switch(classes[c]) { //and we test if the current class of the current input is one of the classes we're interested in
case "validate-text": //if it is a text
test=reText; //the variable "test" will contain the RegExp we want to use
break;
case "validate-date": //same for a date
test=reDate;
break;
case "validate-number": //and same for a number
test=reNumber;
break;
default: //if the class is not something we want, nothing to do
break;
} //end switch
} //end classes loop
//here test is either null (no "validate-something" class found for the current input), or it contains the RegExp telling us the kind of input we must validate.
if(test!=null && !input.value.match(test)) { //if it is not null and if the input's value does not match the RegExp
message.push(input.title); //we add the field to the "message" array
}
} //end input loop
if(message.length>0) { //if the arary is not empty, we display a confirm box
return confirm("Please correctly fill the following field(s), or click OK to send an incomplete form:\n"+message.join("\n"));
}
//otherwise, the form is correctly filled, we return true to submit the form
return true;
}

Categories