javascript not running onBlur - javascript

The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here. Just trying to test a simply validation.
<div class="cell">
<label>DOB</label><br>
<input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">
</div>
<script type="text/javascript">
function checkForm(form)
{
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(form.dob.value != '' && !form.dob.value.match(re)) {
alert("Invalid date format: " + form.dob.value);
form.dob.focus();
return false;
}
alert("All input fields have been validated!");
return true;
}

<div class="cell">
<label>DOB</label><br>
<input id="startdate" type="text" placeholder="01/01/1980" onblur="checkForm()">
<script>
function checkForm()
{
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
var date = document.getElementById("startdate").value;
alert(date);
if(date != '' && !date.match(re)) {
alert("Invalid date format: " + date);
date.focus();
return false;
}
alert("All input fields have been validated!");
return true;
}
</script>
</div>

Related

Javascript date validation not working

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

JQuery validate date between a date range [duplicate]

This question already has answers here:
Validate that end date is greater than start date with jQuery
(16 answers)
Validate end_date is after start_date [duplicate]
(1 answer)
Closed 5 years ago.
I've an input field where users can insert a date between a date range.
So I added a new method on JQuery validator object:
$.validator.addMethod("dateRange", function(value, element, from, to){
try {
var date = new Date(value);
if(date >= from && date <= to)
return true;
} catch(e) {
}
return false;
}
Then I added a new class rules:
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {fromDate, toDate}
}
});
And finally I added the class to the input:
$("#myField").addClass("myDateFieldRangeValidate");
So, how can I pass the two dates to the validation function?
UPDATE: Added a code snippet
$.validator.addMethod("dateRange", function(value, element, from, to){
try {
var date = new Date(value);
if(date >= from && date <= to)
return true;
} catch(e) {
}
return false;
});
var fromDate = new Date("2017-02-01");
var toDate = new Date("2017-12-31");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {fromDate, toDate}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#btnValidate").click(function(){
$("#frm1").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form id="frm1">
Date <input type="text" id="myField">
<input type="button" id="btnValidate" value="Validate">
</form>
Thanks to Arun P Johny, I post here his fiddle:
$.validator.addMethod("dateRange", function(value, element, params) {
try {
var date = new Date(value);
if (date >= params.from && date <= params.to) {
return true;
}
} catch (e) {}
return false;
}, 'message');
var fromDate = new Date("2017-02-01");
var toDate = new Date("2017-12-31");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {
from: fromDate,
to: toDate
}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#frm1").validate();
$("#btnValidate").click(function() {
console.log($("#frm1").valid())
});
jQuery(function($) {
var validator = $('#myform').validate({
rules: {},
messages: {}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<form id="frm1">
Date
<input type="text" id="myField" value="16 Feb 2017">
<input type="button" id="btnValidate" value="Validate">
</form>
Here is a way to have jQuery validator with the feature to give the start date and the end date
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script>
$( document ).ready(function() {
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
var startDate= new Date(jQuery(element)[0].attributes['data-rule-startDate'].value);
var endDate= new Date(jQuery(element)[0].attributes['data-rule-endDate'].value);
var d = new Date(value);
console.log(d)
return (d.getTime() <= endDate.getTime() && d.getTime() >= startDate.getTime())
}, "Please enter a valid date."
);
$('#frm1').validate();
});
</script>
<html>
<form id="frm1">
Date <input type="text" id="myField" name="myField" data-rule-optdate="true" data-rule-startDate="2017-12-12" data-rule-endDate="2018-12-12">
</form>
</html>

Accept date from user within particular range

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;
}

JavaScript-form validation

I am doing some form validation in JSP, on click on submit button "validate_access()" function is not called or not working. Sometimes this function displays a alret box and then stop doing any thing . Please tell what is wrong with this piece of code.Here is a piece of code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Data management system</title>
<script language="JavaScript" type="text/javascript">
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(document.myform1.MISDN.value=="" && document.myform1.Issue.value=="" && document.myform1.SR.value=="" && document.myform1.date.value=="")
{
alert("Manadotry fields should not left blank");
document.myform1.MISDN.focus();
document.myform1.Issue.focus();
document.myform1.SR.focus();
document.myform1.date.focus();
return false;
}
else if(!a.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.MISDN.focus();
return false;
}
else if(!(b.value.match(numbers) && b.value.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myform1.Issue.focus();
return false;
}
else if(!c.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.SR.focus();
return false;
}
else if(!d.value.match(Datee))
{
alert('Please input correct date');
document.myform1.date.focus();
return false;
}
else
return true;
}
</script>
</head>
<body>
<div class="main">
<div class="header"></div>
<div class="continer">
<div class="myform1" style="height:200px; width:300px; float:left;">
<h2>1344 Access</h2>
<form name="myform1" action="access.jsp" method="get" onsubmit="return validate_access()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>Issue:<input type="text" name="Issue" maxlength="13">
<br/>SR:<input type="text" name="SR">
<br/>Date:<input type="text" name="date" value="dd/mm/yy">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
<div class="myform2" style="float:left;height:200px; width:300px;">
<h2>O.C.S</h2>
<form name="myform2" action="ocs.jsp" method="post" onsubmit="return validate_ocs()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>SR:<input type="text" name="SR">
<br/>REASON:<input type="text" name="reason">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
</div>
</div>
</body>
Problems in your javascript are:
the first if condition check is wrong you mean || in place of &&.
then next when you call match method on empty string a error probably raise like:
Uncaught TypeError: Cannot read property 'match' of undefined
you calling .focus() continuously that doesn't making any sense, call once with a condition check.
There is something wrong in this line:var a = document.forms["myForm1"]["MISDN"].value;
Look at your source code, your form name is "myform1" not "myForm1".
JavaScript is case sensitive.
http://en.wikipedia.org/wiki/JavaScript_syntax
in your js:
document.forms["myForm1"]
but in your form(html) it is:
<form name="myform1"
Try this:
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(a == "" && b == "" && c == "" && d == "")
{ //as you have default value for d (date field), this condition will never match;
//either you can remove default value or provide different logic
alert("Manadotry fields should not left blank");
document.myForm1.MISDN.focus();
document.myForm1.Issue.focus();
document.myForm1.SR.focus();
document.myForm1.date.focus();
return false;
}
else if(a == "" && !a.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.MISDN.focus();
return false;
}
else if(!(b.match(numbers) && b.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myForm1.Issue.focus();
return false;
}
else if(!c.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.SR.focus();
return false;
}
else if(!d.match(Datee))
{
alert('Please input correct date');
document.myForm1.date.focus();
return false;
}
else
return true;
}
Your mistakes:
(i) form name spelling mistake (caseSensitive)
(ii) you used HTMLElement.value.value to check (in if conditions)
For example:
var a = document.forms["myForm1"]["MISDN"].value;
a.value.match(numbers); // it simply means HTMLElement.value.value (which will never work)

JSP Java Script validation not working

I wrote a java script code in a JSP page,But when i try to submit the Page, my javascript validation code is not getting fired,Could any one help me what went wrong?
Here My Code:
<html>
<center><h3>Employee Absent Report</h3></center>
<head>
<script language="javascript" type="text/javascript">
function onFormSubmit(){
var countErrors = 0;
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form" action="FormServlet" method="get" onsubmit="return onFormSubmit(); ">
<center>
<div id="formErrors" class="error"></div>
FromDate:
<input type="text" name="startdate" id="startdate"/>
<div id="divStartDate"></div>
<br>
ToDate:
<input type="text" name="todate" id="todate"/>
<div id="divExpiryDate"> </div>
<br>
<input type="submit" value="submit"/>
</center>
</form>
</body>
</html>
is there a method "IsEmpty" in javascript? I think that's the problem. If you have that defined in some other place, try running your code in Firefox and watch Error Console for errors.
Looks like a logical error to me. Try replacing this:
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
with:
if (endDt.length==0) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt.length==0) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Do the validation this way
if (endDt === "") {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt === "" ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Hope this helps!
this is the working modified code
<script>
function onFormSubmit(event){
var countErrors = 0;
event.preventDefault();
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if ( IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
eFlag = true ;
}
if (IsEmpty(strDt)==true ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
eFlag = true;
}
if(eFlag)
{
return false;
}
return true;
}
function IsEmpty(input)
{
if(input.replace(/^\s+|\s+$/g,"") === "") {
return true;
}
return false;
}

Categories