I have a registration form with date of birth as one of the fields, I have written a function for future date which has to be invalid. But when the user puts a future date it still submits the form, although alert is being made to the user.
This is the function for alert, and its working fine.
var user_birth_year=document.getElementById("birth_year").value;
var user_birth_month=document.getElementById("birth_month").value;
var user_birth_day=document.getElementById("birth_day").value;
var userDate = new Date(user_birth_year,user_birth_month-1,user_birth_day);
var currentDate = new Date();
var res="Invalid date";
if(currentDate.getTime() < userDate.getTime() ) {
document.getElementById('registererror').innerHTML = "<span class='errorMsg'>"+res+"</span>";
document.getElementById('registererror').style.display = 'block';
} else {
document.getElementById('registererror').style.display = 'none';
}
Usually to stop the submit of a form, you need to return false on the form submit event.
Related
I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating
I'm trying to validate a form here and I'm almost done. The only issue is I can't figure out a way of validating the dates field to check whether the date that has been put in hasn't passed. It has to be done through Javascript... btw, here is the HTML:
<label for="reservationDate">Date of reservation (DD/MM/YYYY):</label>
<input type="text" id="date" name="date" onblur="validateDate(date)">
<span id="dateError" style="display: none;">Please enter your date of reservation in this format DD/MM/YYYY</span>
Here is the Javascript:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
if(re.test(document.getElementById(x).value)){
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Hope someone can help :)
Here's some code to make this a specific answer to suit your needs:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
var entered = new Date(document.getElementById(x).value);
var today = new Date();
if( entered > today ) {
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Here is the working, tested code: http://jsfiddle.net/digitalextremist/rwhhg/1/
Some past answers which are pieces but not really the whole deal:
Check if date is in the past Javascript
Validate that end date is greater than start date with jQuery
Javascript to validate date entered
I'm checking a date entered with a datepicker control in jquery from an Html.TextBoxFor helper:
<%=Html.TextBoxFor(c => Model.mydate, new { #class = "datepicker", maxlength = 10, #onBlur = "chkDate"})%>
The datepicker mask for the textbox appears to be MM/DD/YYYY . So, my script checks for an underscore and displays an error. This works if the user igonores the datepicker and tries to enter a date freehand but not if the datepicker is used. When a date is chosen, the value passed to my script is still underscores and no value. Here's my script:
<script type="text/javascript">
$(document).on("blur", "input[name=mydate]",
function chkDate() {
var len = $("input[name=mydate]").val().length;
var date = $("input[name=mydate]").val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
There's an event onChange associated with datepicker. Is this what I should be using? If so, how do I specify that in my helper and what script changes do I need to make?
Try this,
$(document).on("change", "input[name=mydate]",function (){
var len = $(this).val().length;
var date = $(this).val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
Assuming you are using the popular JQuery UI's Datepicker, weirdly enough they are not entitled events but callbacks that can handle this event. See onSelect or onClose.
I need to call a function by clicking a button. The button is on an aspx page and the function is on a .js page.
This is the code I use for my button:
<asp:LinkButton ID="lnkBTNSubmit" runat="server" CssClass="buttonlink"
OnClick="lnkBTNSubmit_Click" OnClientClick="onBtnSubmitClick();">Submit</asp:LinkButton>
and this is my function:
function onBtnSubmitClick() {
var startDate = document.getElementById('<%= txtATrendStartDate.ClientID %>').value;
var endDate = document.getElementById('<%= txtATrendEndDate.ClientID %>').value;
checkDateRange(startDate, endDate);
}
function checkDateRange(start, end) {
// Parse the entries
var startDate = Date.parse(start);
var endDate = Date.parse(end);
// Make sure they are valid
if (isNaN(startDate)) {
alert("The start date provided is not valid, please enter a valid date.");
return false;
}
if (isNaN(endDate)) {
alert("The end date provided is not valid, please enter a valid date.");
return false;
}
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (endDate - startDate) / (86400000 * 7);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
return true;
}
Please note that the function is on an another .js page.
To call the function in the other js file you have to include a reference to the js file on your page.
Example:
Put this in your head tag:
"script src="SomeOtherJSFIle.js" type="text/javascript"/script"
I have form field and that form field gets submitted to the next page with the following javascript code.., the code is working fine in firefox but the form not getting submited in internet explorer.
function addarray(formId)
{
var ara = tmm.length;
//alert(ara);
for(var sds=0; sds < tmm.length; sds++)
{
var sss = tmm[sds];;
ara = ara+"*#*#*"+sss;
//alert(ara);
if(sss <= 0)
{
alert("\n\n\nYou should have atleast one submenu \n for each main menu \n\n");
return false;
}
}
var ddf = document.blcname.getElementsByTagName("input");
var i = 0;
while(i < ddf.length)
{
var dddd = ddf[i].type;
var vla = ddf[i].value;
//alert(i+"----"+vla+"-----"+dddd);
if(dddd=="text"){
if(vla == "")
{
//alert("Please fill all the required fields....");
return false;
}
}
i=i+1;
}
var setform = document.getElementById('arav');
setform.value = ara;
var formObj = document.getElementById(formId);
formObj.action = "get-code.php";
formObj.submit();
//document.blcname.submit();
}
thanks in advance
Try alternate ways of getting to this form. Give the form HTML id and a name attribute
Also watch out if you're using frames and the form is inside of a frame.
eg.
document.forms[0].submit() //if its the first form in the document
document.forms[1].submit() //if its the second form in the document
document.formName.submit() //using the name attribute.