PHP Form Submits Before Javascript Validation - javascript

I'm having a somewhat common problem of getting my form to validate before submission. I've tried several variations on the same theme and with no dice: at best I could get nothing to submit, but usually my form just ignores codes and submits anyway.
Chances are I'm missing something small but I'd appreciate any help! Essentially just trying to make sure the name isn't empty here (return true; is pointless IIRC but I was getting desperate haha). Once I can get some basic level of validation down it just comes down to coding the JS for more complicated maneuvers so this should be good enough, i hope. Thanks!
<script>
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else {
return true;
}
alert("Bla");
}
</script>
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm(); return false;"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>

You're making it to complex.
JavaScript:
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else { return true; }
}
HTML:
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm()"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>

Your validation works fine, but because you are trying to
document.getElementByID("JSError").innerHTML
instead of
document.getElementById("JSError").innerHTML
JS throws an error and never reaches your "return false".
You can easily see this, when you use your browsers console output. (In firefox and chrome press F12).
Example fiddle: http://jsfiddle.net/6tFcw/

1st solution - using input[type=submit]
<!-- HTML -->
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
// JavaScript
function validateForm(){
var target = document.getElementById("name"); // for instance
if(target.value.length === 0){
alert("Name is required");
return false;
}
// all right; submit the form
return true;
}
2nd solution - using input[type=button]
<!-- html -->
<input type="button" name="submit" id="submit" value="Submit" />
// JavaScript
window.onload = function(){
var target = document.getElementById("name");
document.getElementById("submit").onclick = function(){
if(target.value.length === 0){
alert("Name is required");
}else{
// all right; submit the form
form.submit();
}
};
};

Related

Html Form Unable to Validate Inputs using JavaScript

I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

JavaScript validation file not working: "ReferenceError: validateForm is not defined" (html linked)

(edit: code updated)
I am running into an error, when trying to clientside-validate with JavaScript that the user has filled in the forms correctly in the Register part of my HTML form.
The HTML and JS file are pretty straightforward:
(Fiddle)
JavaScript and HTML:
function validateForm() {
var name = document.getElementById('username').value;
var email = document.getElementById('email').value;
if (name == null || name == "" || checkIfSpaceOnly(name) == false) {
return false;
}
else if (email == null || email == "" || validateEmail(email) == false){
return false;
}
else
return true;
}
//other methods used in validateForm:
function checkIfSpaceOnly(input) {
var re = /\S/;
return re.test(input);
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
window.onload = function()
{
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener("click", validateForm);
}
<!DOCTYPE html5>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="design.css">
</head>
<div class = "body1">
<div class = "forms" id="forms">
<h2>Log in</h2>
<form name='loginform' action='login.php' method='POST'>
<input type='email' name='email' placeholder="Email" ><br>
<input type='password' name='password' placeholder="Password" ><br><br>
<input type='submit' value='Log in'><br><br>
</form>
<hr>
<br><h2>Register</h2>
<form onsubmit="" name="register" action="register.php" method="POST" onsubmit="return validateForm()">
<input type="text" name="username" class="form-control" placeholder="Username" id="username"><br>
<input type="email" name="email" class="form-control" placeholder="Email" id="email"/><br>
<input type="password" name="password" class="form-control" placeholder="Passwoord"><br>
<br>
<input type="submit" name="submit" id="submit" value="Create user">
</form>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</html>
So the problem is, it's like the JS file isn't used at all by the HTML file. The form gladly registers any user, no matter if they fulfill the JavaScript file's if conditions or not.
I checked the console, and it says (when the user has been registered), "ReferenceError: validateForm is not defined".
Except checking that the file directories are correct of course, I have searched and read about both general HTML JS form validation Errors, 20-something "similar question" on here, and that specific ReferenceError. I've changed values, names, moved code parts around.... but I can't seem to find the problem and don't know what to do, although it feels like it's just a simple mistake somewhere in the code.
You have 3 problems
Your fiddle is setup incorrectly; all the code is wrapped in an onload which means your validateForm method is not accessible from HTML markup
You have 2 onsubmit attributes in the form - the second contains what it should contain but is being ignored because of the first
You assign the event handler both in markup and in code. Choose one, stick with it.
When you fix these 3 problems, it works as expected and does not submit the form if anything goes wrong (ie, false is returned from validateForm)
https://jsfiddle.net/spwx1rfd/7/
Please check the if condition, you have made a mistake.
Wrong code
if (uName == "") || checkIfSpaceOnly(uName) == false) {
return false;
}
Right code
if (uName == "" || checkIfSpaceOnly(uName) == false) {
return false;
}

Redirect the Page after Form is Submitted - Javascript

Q1. How could I place a code that can redirect the page after the form submitted??
Q2. I am looking some article about return value, anyone please recommend some good article for me.
<form method="post" name="formName">
<input type="text" value="Name" name="cName">
<br>
<input type="submit" onClick="return fValidator(this)">
</form>
<script language="javascript1.8.5" type="text/javascript">
function fValidator(){
var vName = document.formName.cName;
var nameReg = /^[a-zA-Z]+$/;
if (vName.value != ''){
if (vName.value.match(nameReg)){
alert("Your form is sumitted now!");
return true;
location.replace("http://www.w3schools.com");
} else{
alert("Alphabet only!");
return false;
}
} else{
alert("Fill the mandatory field!");
return false;
}
}
</script>
Use "onsubmit".
Eg: <form onsubmit="myFunction()">
This lets you to control the page behaviour after submitting the form.

How to submit a button when the form becomes visible

Im trying to send the user to a payment URL if the user validate is true and that works fine.
but i have another form thats hidden from the beginning and if the validate is true i unhide the form and then i need the btn with id #openPaymentButton to get sbumitted
if(data.success == true)
{
//Vis betalings vindue knap og klik på knappen
$scope.hideEpayBtn = false;
$("#openPaymentButton").click();
console.log('virker');
} else {
alert("Error");
}
<form action="https://ssl.ditonlinebetalingssystem.dk/integration/ewindow/Default.aspx" ng-if="hideEpayBtn == false" method="post">
<input ng-hide="hideEpayBtn" id="openPaymentButton" type="submit" value="">
</form>
First of all the question is not clear. So far I understand, you are talking about some validation.
If you question bit specific, I can give you an appropriate answer. This answer is from my guess based on your question.
May be you can use something like this in your form
<form name="formName" data-ng-submit="yourfunction(formName.$valid)" novalidate>
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
<form action="https://ssl.ditonlinebetalingssystem.dk/integration/ewindow/Default.aspx"
data-ng-hide="success == false" method="post">
<input data-ng-hide="success == ''" id="openPaymentButton" type="submit" value="">
</form>
In you angular controller:
$scope.success = false;
$scope.yourfunction= function (isValid) {
if (isValid) {
$scope.success = true;
serviceFor.addNewProject($scope.inputObject);
}
} else {
$scope.success = true;
$scope.failMessage = "Please fill up all the fields";
}
};
This is my best guess for what you are asking for. Please let me know if it is ok.

Javascript not working on submit

In my HTML file, I have the following script:
<script language = "javascript">
function validation(){
var x = document.forms["form"]["fieldx"].value;
var y = document.forms["form"]["fieldy"].value;
var act = document.forms["form"]["action"].value;
if(x == null && y == null && act == "delete"){
var z = confirm("Fields have no input. Proceed at your own risk");
if(z==true) return true;
else return false;
}
}
</script>
And the form:
<form name="form" onsubmit="return validation()" action="cgi-bin/process.cgi" method="GET">
<input type="text" name="fieldx" />
<input type="text" name="fieldy" />
<input type="submit" name="action" value="insert" />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="update" />
</form>
with two input fields named fieldx and fieldy, and a submit type named action which can take any value (i.e. insert, delete and update) as shown above.
Supposedly, when the delete (and only the delete) button is clicked, it will check if there are any inputs inputed on both fields. If there are none, Javascript will prompt and ask the user if it wants to proceed. If he/she clicked yes, well, the process.cgi will be executed and if not, it will just return to the HTML page. However, when I clicked delete, there was no prompt and the cgi was executed.
You have two problems:
First:
x == null && y == null
The values of the fields will never be null. If nothing has been input into them, then their value will be a empty string (i.e. ""). So you need to compare against that and not null.
Second:
document.forms["form"]["action"].value
You have multiple controls named action, so document.forms["form"]["action"] will be a NodeList (which is like an Array). It won't be a single element, and value will always be undefined.
There is no way to tell, from a submit event, which form control was used to activate the form.
Use an onclick handler on the input you care about instead.
<script>
function validation(){
var x = document.forms["form"]["fieldx"].value;
var y = document.forms["form"]["fieldy"].value;
if(x == "" && y == ""){
return confirm("Fields have no input. Proceed at your own risk");
}
}
</script>
and
<input type="submit" name="action" value="delete" onclick="return validation();">
A more modern way to write it would be along these lines:
<form action="cgi-bin/process.cgi">
<input type="text" name="fieldx">
<input type="text" name="fieldy">
<input type="submit" name="action" value="insert" />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="update" />
</form>
<script>
document.querySelector('input[value=delete]').addEventListener('click', validate);
function validate(event) {
var elements = this.form.elements;
if (elements.fieldx.value == "" && elements.fieldy.value == "") {
if (!confirm("Fields have no input. Proceed at your own risk")) {
event.preventDefault();
}
}
}
</script>

Categories