HTML forms validation with a FILE input object - javascript

I've been pulling my hair out trying to add a FILE input object to a form on one of my intranet web pages. I saw this article (HTML <input type='file'> File Selection Event) and wondered if this is why even though I have an [onSubmit] handler linked in the tag, as soon as I add the object, it no longer fires the onSubmit event at the form level. Is there a way to tie it all together so I can still validate the other input objects on the same form before going to the handler URL? I need this to work in IE8, and Chrome 20+ mostly. Any help would be greatly appreciated.
Javascript:
function CheckForm(theForm) {
var formName = "form1";
var formx = document.getElementById(formName);
if (formx.appname.value == "") {
alert("Please enter the \"APPLICATION NAME\"...");
formx.appname.focus();
return(false);
}
if (formx.vendor.value == "") {
alert("Please enter the \"VENDOR NAME\"...");
formx.vendor.focus();
return(false);
}
if (formx.srcfile.value == "") {
alert("Please select the "\FILE NAME\"...");
return(false);
}
return (true);
}
HTML:
<form name="form1" id="form1" method="post" language="JavaScript" onSubmit="return CheckForm(this);return false;" action="appform2.asp">
<table width="100%" border="0" cellpadding="4" cellspacing="1" bgcolor="#c0c0c0">
<tr>
<td>Product Name / Version</td>
<td>
<input type="text" id="appname" name="appname" size="50" maxlength="255"/>
</td>
</tr>
<tr>
<td>Vendor Name</td>
<td>
<input type="text" id="vendor" name="vendor" size="50" maxlength="255"/>
</td>
</tr>
<tr>
<td>Source Binaries</td>
<td>
<input type="file" name="srcfile" id="srcfile"/>
</td>
</tr>
</table>
<p>
<input type="reset" name="b2" id="b2" value="Reset"/>
<input type="submit" name="b1" id="b1" value="Submit"/>
</p>
</form>

Related

Why is html input field not being validated before post

So in the html body I have both
<script type="text/javascript">
function validateMelco(form) {
toReturn=true;
if (form.melco.value.length==0) {
alert("Please enter your Melco serial no");
toReturn=false;
}
return toReturn;
}
</script>
and
<tr>
<td valign="top"><b>SongKong for Melco (Melco discount)</b>
</td>
<td valign="top">£40 ($50 USD)
</td>
<td valign="top">
<form name="paypalpro" action="https://www.paypal.com/cgi-bin/webscr" onsubmit="return validateMelco()" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="5UC5NAYZ6JZR8">
<input alt="PayPal" type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" border="0" name="submit">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
Melco Serial No:<input type="textfield" name="melco"/>
</form>
</td>
</tr>
Yet a user can click on the button without entering anything into the input field, no alert is displayed and the form is posted. Why isn't the JavaScript validation kicking in?
Change the line
<form name="paypalpro" action="https://www.paypal.com/cgi-bin/webscr" onsubmit="return validateMelco()" method="post">
to
<form name="paypalpro" action="https://www.paypal.com/cgi-bin/webscr" onsubmit="return validateMelco(this)" method="post">
You're calling the function with no arguments, but it expects an argument that identifies the form. So it can't do anything.
<!DOCTYPE html>
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<tr>
<td valign="top"><b>SongKong for Melco (Melco discount)</b>
</td>
<td valign="top">£40 ($50 USD)
</td>
<td valign="top">
<form name="paypalpro" action="https://www.paypal.com/cgi-bin/webscr" onsubmit="return validateMelco()" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="5UC5NAYZ6JZR8">
<input alt="PayPal" type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" border="0" name="submit">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
Melco Serial No:<input type="textfield" name="melco"/>
</form>
</td>
</tr>
<script>
function validateMelco(form) {
toReturn=true;
if (document.forms["paypalpro"]["melco"].value == "") {
alert("Please enter your Melco serial no");
toReturn=false;
}
return toReturn;
}
</script>
</body>
</html>
The form object has not been passed to the function "validateMelco()" for accessing the form elements . So I have used the javascript document object to access the form using 'document.forms["paypalpro"]["melco"]'.

jQuery .submit() function not working inside of .ready() function

I have a Classic ASP application which uses a dynamic table to submit inventory information. All of my functions inside the jQuery script until I get down to the .submit() part. I am trying to check that an employee number is given as well as that there are no blank fields before the form is submitted. Any help?
Here's my form:
<form name="filter" id="theForm" method="GET" action="InventoryIssues.asp">
<table class="normsideBG" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td class="bigger headerBG" align="center" colspan=6>
<b>Inventory Issues</b>
</td>
</tr>
<tr class="norm">
<td>
</td>
</tr>
<tr class="norm">
<td class="norm" align ="right">
<b>Enter Employee Number: </b><input type="text" id="employeeNum" name="employeeNum" value = "<%=employeeNum %>" />
<select id="hiddenBox" name="hiddenBox" style="display: none" >
</select>
<input type="hidden" name="action" value="set_filter">
</td>
</tr>
<tr>
<td class="norm">
To add more records click 'Add New Record'. Submit when all records are completed.
<br />
<br />
<input style="text-align: right" type="hidden" name="hasValues" value="false" />
<center>
<button type="button" id="addRec">Add New Record</button>
<button type="button" id="delRec">Remove Last Record</button><br /><br />
<input type="submit" id="sub" name="submit" class="norm" value="Submit"/>
</center>
</td>
</tr>
</table>
<table id= "tb1" class="norm sideBG" name="recordTable" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td>
<b><u>PART #</u></b>
</td>
<td>
<b><u>LOCATION</u></b>
</td>
<td>
<b><u>QUANTITY</u></b>
</td>
<td>
<b><u>WHERE USED</u></b>
</td>
</tr>
<tbody class="theRow" id="theRow">
<tr>
<td class="norm">
<label id="partLabel" style="color : red;"></label>
<br />
<input type='text' name='txtbox0[]' id='txtbox0[]' onchange="javascript: changeLabel(this)" />
</td>
<td class="norm">
<select id="txtbox1[]" name="txtbox1[]" >
</select>
</td>
<td class="norm">
<input type='text' name='txtbox2[]' id='txtbox2[]' />
</td>
<td class="norm">
<input type='text' name='txtbox3[]' id='txtbox3[]' />
</td>
</tr>
</tbody>
</table>
</form>
Here is my jQuery
'<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var ctr = 0;
$("#addRec").click(function ()
{
var clone = $("#tb1 > tbody.theRow:last").clone();
clone.find("input").val("");
clone.insertAfter("#tb1 > tbody.theRow:last");
$("#hasValues").val(true);
});
$("#delRec").click(function ()
{
$("#tb1:last tbody.theRow:last").remove();
});
alert("at least this works");
$("form#theForm").submit(function(event)
{
var blankEmployeeNum;
var blankFields = false;
var inp = $("#employeeNum");
if (inp.val().length == 0 || inp.val() == Null)
{
alert("blank empoyee num");
blankEmployeeNum = true;
}
else
{
alert("the employee num has a value");
blankEmployeeNum = false;
}
$("#tb1 tr").each(function()
{
$("td", this).each(function()
{
var value = $(this).find(":input").val()
if (value.val().length == 0 || value.val() == Null)
{
alert("there's a blank field");
blankFields = true;
}
});
});
if (blankEmployeeNum)
{
alert("Please go back and enter an employee number before submitting.");
event.preventDefault();
}
else if (blankFields)
{
alert("One or more of the fields submitted were blank. Please go back and try again.";
event.preventDefault();
}
});
});
'
There is a script error
Update
alert("One or more of the fields submitted were blank. Please go back and try again.";
to
alert("One or more of the fields submitted were blank. Please go back and try again.");
You are missing the closing bracket.
Please note there are some more script errors too. Please resolve then by checking in console.
I have found out few for you like changeLabel is not a function etc. You really need to work a lot on the script. There are many errors.
You need to call event.preventDefault() at first inside the submit function, otherwise the event bubbles up and the form is submitted.
$("form#theForm").submit(function(event) {
event.preventDefault();

Trouble submitting my form (with jQuery validation) to the same page with $_POST

I have a form that uses a jQuery system to verify the input. With the default way it works, if there are no errors, it will submit. I am pretty bad with JavaScript, so my question is:
How would I go about making this submit to the same page and put the inputs in the $_POST variable, so it can execute the PHP code to handle the data, while having the jQuery validation working?
What I've noticed:
The type for the submit button must be set to type="button" for the validator to work
Having the type set to button, makes the <form> not submittable
PHP Snippet to validate the input (see if it actually posted into the $_POST variable):
if(isset($_POST)){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
echo $username."<br>".$email."<br>".$password;
}
The script for the form:
<form action="" method="post">
<table border=0 id="form" style="padding:10px;">
<tr>
<td>
Username
</td>
<td align=left>
<input name="username" type="text" size="20" jVal="{valid:function (val) { if (val.length < 3) return 'Invalid Name'; else return ''; }}">
</td>
</tr>
<tr>
<td>
Email address
</td>
<td align=left>
<input name="email" type="text" size="40" jVal="{valid:/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/, message:'Invalid Email Address'}" jValKey="{valid:/[a-zA-Z0-9._%+-#]/, cFunc:'alert', cArgs:['Email Address: '+$(this).val()]}">
</td>
</tr>
<tr>
<td>
Password
</td>
<td align=left>
<input name="password" id="password" type="password" jVal="{valid:function (val) { if (val.length < 4) return false; else return true; }, message:'Password of 4 or more characters required'}">
</td>
</tr>
<tr>
<td style="padding-right:20px;">
Verify password
</td>
<td align=left>
<input name="passwordconfirm" id="passwordVerify" type="password" jVal="{valid:function (val) { if ( val != eval('$(\'#password\').val()') ) return false; else return true; }, message:'Password and Verify Password Must Match'}">
</td>
</tr>
<tr>
<td>
<input type="hidden" name="antispam" value="banana" />
<script>
var antiSpam = function() {
if (document.getElementById("antiSpam")) {
a = document.getElementById("antiSpam");
if (isNaN(a.value) == true) {
a.value = 0;
} else {
a.value = parseInt(a.value) + 1;
}
}
setTimeout("antiSpam()", 1000);
}
antiSpam();
</script>
</td>
</tr>
<tr>
<td></td>
<td>
<input id="submitButton" type="button" value="Click here to register!" onClick="if ( $('#form').jVal({style:'blank',padding:8,border:0,wrap:false}) ){ this.form.submit;}">
</td>
</tr>
</table>
</form>
If needed, the files corresponding to the jVal system (validation) can be found here, but they are most likely not needed.
Thanks ahead
PS. Please do not go saying to "narrow down the problem", when I had it narrowed down and posted the specific code snippets, I was told to post the entire code, so here it is.
Use HTML5 validation and <input> types. Your browser can validate e-mail addresses better than you can, for example.
Drop the spam protection; it will prevent actual users from using your page. Use reCAPTCHA.
Don’t use tables for layout. Please? At the very least, use CSS instead of the align attribute.
Don’t assume that everyone’s name is at least three characters long.
<form method="POST">
<table border="0" id="form" style="padding: 10px;">
<tr>
<td>
Username
</td>
<td align="left">
<input name="username" type="text" size="20" required />
</td>
</tr>
<tr>
<td>
Email address
</td>
<td align="left">
<input name="email" type="email" size="40" required />
</td>
</tr>
<tr>
<td>
Password
</td>
<td align="left">
<input name="password" id="password" type="password" required />
</td>
</tr>
<tr>
<td style="padding-right:20px;">
Verify password
</td>
<td align="left">
<input name="passwordconfirm" id="password-confirm" type="password" required />
</td>
</tr>
<tr>
<td></td>
<td>
<button>Click here to register!</button>
</td>
</tr>
</table>
</form>
How would I go about making this submit to the same page and put the
inputs in the $_POST variable, so it can execute the PHP code to
handle the data, while having the jQuery validation working?
You can post to the same page using PHP_SELF. Move the id from your table and add it to your form and use it to submit your form in the javascript code
<form id='form' action="<?php print $_SERVER['PHP_SELF'] ?>" method="post">
$('#form').submit() //instead of this.form.submit();
Also, instead of isset($_POST) you should use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}

Making validation for both text field and checkbox

Please can I ask for help with my form. I am wanting to make both the text fields and check box required fields. The check box is validating, all I need now is for the text fields to require validation. I'm using javascript.
HTML:
<form name="form" method="post" action="result.php" onSubmit="return checkme()">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Name: </td>
<td> <input name="Name" type="text" id="Name" size="20"></td>
</tr>
<tr>
<td>Email: </td>
<td> <input name="Email" type="text" id="Email" size="20"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="checkbox" name="agree" value="agree_terms"> I agree to the terms</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Clear"></td>
</tr>
</table>
</form>
Javascript:
<script language="JavaScript" type="text/JavaScript">
<!--//hide script
function checkme() {
missinginfo = "";
if (!document.form.agree.checked) {
missinginfo += "\n - You must agree to the terms";
}
if (missinginfo != "") {
missinginfo ="__________________________________\n" +
"Required information is missing: \n" +
missinginfo + "\n__________________________________" +
"\nPlease complete and resubmit.";
alert(missinginfo);
return false;
}
else {
return true;
}
}
</script>
Add this JS code for validating the text field
if(document.form.Name.value==""){
missinginfo += "Required field";
}
Same for e-mail field also.
If you convert you doctype to <!DOCTYPE html> then you can use
required="true"
It will be implemented as follow
<input name="Name" type="text" id="Name" size="20" required="true">
Most browsers support HTML5. Alternatively make use of jQuery validation which is fairly simple to use.

Javascript onClick validate not firing

First off my apologies for how disgusting this code is, it is not my choice by far, following orders from my boss and others in my team have never done anything web before. Really isn't good to miss the start of a project!
Basically I want to validate a couple of inputs before progressing to the next page via a submit button. There is no form in use so I am trying to use onClick for the submit button to launch the validate function. Can anybody see what is wrong with the code below (other than it being awful, from the standpoint of getting it to work as wanted.)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- #include file="includes/header.asp" -->
<Center>
<tr>
<td width="100%" height="300" align="center">
<table width="100%" id="table01">
<Tr>
<Td height="30" align="center" colspan="2" style="background-image:url(img/table_header.jpg);background-repeat:repeat-x" >
<font class="table_header">Password Reset</font>
</td>
</tr>
<tr>
<Td align="center" height="150" valign="middle">
<font class="table_grey">
Please select one of the methods below to reset your password.
<br><br>
<form name="radioq"align="center">
<input type="radio" name="levels" value="level1" onClick="get_radio_value(1);"/> E-mail a new password<br />
<input type="radio" name="levels" value="level2" onClick="get_radio_value(2);"/> Answer secret question<br/>
</form>
<!-- Javascript to handle which table loads below based on radio selection -->
</font>
</td>
</tr>
</table>
<table width="100%" class="table01" id="level1" style="display:none;">
<Tr>
<Td height="30" align="center" colspan="2" style="background-image:url(img/table_header.jpg);background-repeat:repeat-x" >
<font class="table_header">E-mail Address</font>
</td>
</tr>
<tr>
<Td align="center" height="150" valign="middle">
<font class="table_grey">
Please enter your e-mail address and surname.
<br/><br/>
<font class="table_grey">E-mail Address: </font>
<input id="emailinput" size="20" type="text" value="" name="emailinput" />
<br/><br/>
<font class="table_grey">Surname: </font>
<input id="surnameinput" size="20" type="text" value="" name="surnameinput" />
<!-- Javascript to handle incorrect surname/email -->
</font>
</td>
</tr>
<tr>
<td align="right">
<a style="text-decoration:none;"href="password_email_success.asp"><button class="smallbutton" onClick="return validatemail();" type="submit" value="Login" name="submit" class="submit" /><span>Next</span></button></a>
</td>
</tr>
</table>
<table width="100%" class="table01" id="level2" style="display:none;">
<Tr>
<Td height="30" align="center" colspan="2" style="background-image:url(img/table_header.jpg);background-repeat:repeat-x" >
<font class="table_header">Secret Question</font>
</td>
</tr>
<tr>
<Td align="center" height="150" valign="middle">
<font class="table_grey">
Please answer your secret question below.
<br/><br/>
<font class="table_grey">What is your mother's maiden name? </font>
<br/><br/>
<font class="table_grey">Answer: </font>
<input id="answerinput" size="20" type="text" value="" name="answerinput" />
<!-- Javascript to handle incorrect surname/email -->
</font>
</td>
</tr>
<tr>
<td align="right">
<a style="text-decoration:none;"href="password_change_success.asp"><button class="smallbutton" type="submit" value="Login" name="submit" class="submit" /><span>Next</span></button></a>
</td>
</tr>
</table>
<br><br>
<!-- #include file="includes/footer.asp" -->
<script language="Javascript">
function get_radio_value(val)
{
val = val - 1;
for (var i=0; i < document.radioq.levels.length; i++){
if(i==val){
document.radioq.levels[i].checked = true;
}
}
for (var i=0; i < document.radioq.levels.length; i++){
if (document.radioq.levels[i].checked)
{
var rad_val = document.radioq.levels[i].value;
document.getElementById(rad_val).style.display = "table";
}
else{
var rad_val = document.radioq.levels[i].value;
document.getElementById(rad_val).style.display = "none";
}
}
}
function validatemail()
{
if ( !isNaN(document.level1.surnameinput.value) )
{
alert("Please enter a valid lastname - text only");
document.level1.surnameinput.focus();
return false;
}
if ((document.level1.emailinput.value == "") )
{
alert("Please enter an email.");
document.level1.emailinput.focus();
return false;
}
return true;
}
Call your validatemail() function at the forms onSubmit event instead of one of the buttons onClick event. This is considered best practise as it runs the validation function even when the form is submitted with the ENTER key as well as all related submit buttons.
<form onSubmit="return validatemail();">
Regadring your submit button, don´t name it "submit" and don´t use the class or any other attributes multiple times on the same element.
<button type="submit" name="submitButton" value="Login" class="smallbutton" />
Also, all the form elements (input, button etc.) should be placed within the <form></form> tags.

Categories

Resources