Form validation script before submission - javascript

There is a form, where on submission the new page is opened, only in case if validation is ok. However, the window is opened in every case, and I guess that validation isnt working, while it is supposed to...
I would appreciate if you could point me to the right direction.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function overallcheck() {
if (!checkjob() || !checkEmail() || !Checkname()) {
writeTo("problemArea", "Error messages area");
return false;
}
if (!Checkname()) {
writeTo("problemArea", "Please inser a valid name");
return false;
}
if (!checkEmail()) {
writeTo("problemArea", "Please inser a valid email");
return false;
}
if (!checkjob()) {
writeTo("problemArea", "Please inser your job");
return false;
}
elsereturn true;
}
function Checkname() {
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkEmail() {
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
}
function checkjob() {
clearElement("problemArea");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
//-->
</script>
</head>
<body>
<form onsubmit=( "return overallcheck();") action="another.html" id=form target="_blank" method="GET">
<table>
<button type="submit" onclick="">submit</button>
</form>
</body>
</html>

Well... That's invalid JavaScript. As NewToJS noted in his comment, elsereturn true; is not correct.
You need to use:
else {
return true;
}
Also, this (onsubmit=( "return overallcheck();")) won't work. You need to do this:
<form onsubmit="return overallcheck();" action="another.html" id="form" target="_blank" method="GET">

Related

Unable to stop form from submitting with empty inputs

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

Form validation doesn't like me

Second edit: OH MY GODS I'M AN IDIOT!!! I was focusing on the javascript and completely neglected the lack of a "result" item in the html...Thanks to those who helped!
Edit: Thanks so far. I corrected the errors that people pointed out but it still doesn't like me. :( My html is below.
I'm following a tutorial on html.net (lesson 16 on Javascript) and I've written it exactly how it's supposed to be written. I even loaded up the javascript file of the working tutorial page and compared (was the same)...then copied it and pasted it into my file just to be sure and it still doesn't work. If anyone could offer an opinion, that'd be wonderful. Code is below:
<html>
<head>
<title>Lesson 16: form validation</title>
<script type="text/javascript" src="lesson16.js"></script>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">Name: </label>
<input type="text" id="txtName" name="txtName" />
</p>
<p><label for="txtEmail">Email: </label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
</body>
</html>
function init()
{
var myForm = document.getElementById("myForm");
myForm.onsubmit = validate;
}
onload = init;
function validate()
{
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid)
{
message = "Thank you, you know how to follow instructions...good for you.";
}
else if (! isRequiredNameSet)
{
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
}
else if (! isRequiredEmailSet)
{
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
}
else if (! isEmailValid)
{
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
function validateRequired(input)
{
var isValid = false;
if (input.length == 0)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function validateEmail(email)
{
var isValid = false;
if (email.indexOf("#") == -1 || email.indexOf(".") == -1)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function writeMessage(text)
{
var paragraph = document.getElementById("result");
if (paragraph.firstChild)
{
paragraph.removeChild(paragraph.firstChild);
}
paragraph.appendChild(document.createTextNode(text));
}
you have IsRequiredNameSet in the else if (in validate function), but it should be isRequiredNameSet.
NOTE: you can chage your validateRequired() ... to function validateRequired(input) { return !!input.length; }
The problem is the line myForm.onsubmit = validate();... where you are invoking the validate function instead os assigning it as a reference to onsubmit
myForm.onsubmit = validate;
The same applies to onload also
onload = init;
Then you have a problem in case of isRequiredEmailSet
function validate() {
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid) {
message = "Thank you, you know how to follow instructions...good for you.";
} else if (!isRequiredNameSet) {
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
} else if (!isRequiredEmailSet) {
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
} else if (!isEmailValid) {
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
Demo: Fiddle

Should I validate my form twice?

My code works perfectly here.
But the problem is that I want to add some code validation so that the form can't be submitted if something is wrong in the code. Here is the code I added:
Jquery code:
var user = document.getElementById('u');
var email = document.getElementById('em');
var pass1 = document.getElementById('p1');
var pass2 = document.getElementById('pa2');
function isEmpty(input) {
if (input.value == "" || input.value == null) {
return true;
} else {
return false;
}
}
function validateform() {
if(isEmpty(user) || isEmpty(email) || isEmpty(pass1) || isEmpty(pass2))
{
alert("All fields are required.");
$("#form").submit(function(event) {
event.preventDefault();
});
if(isEmpty(user))
{
user.focus();
}
else if(isEmpty(email))
{
email.focus();
}
else if(isEmpty(pass1))
{
pass1.focus();
}
else if(isEmpty(pass2))
{
pass2.focus();
}
}
}
I also added an Id to my form:
<form action="m.php" method="post" id="form">
I also added the onsubmit here:
<input name="submit" type='submit' value='Submit' onsubmit="validateform()">
but it is not working, the page just moves to m.php even if all fields are empty. what should I do? should I install the jquery validating plugin and validate twice?
Edit
Here is a Demo
After you check if the field is empty if you return false; then the from will not submit.
Form on submit example.
JavaScript
function validateform() {
if(isEmpty(user))
{
user.focus();
return false;
}
else if(isEmpty(email))
{
email.focus();
return false;
}
else if(isEmpty(pass1))
{
pass1.focus();
return false;
}
else if(isEmpty(pass2))
{
pass2.focus();
return false;
}
}
Your onsubmit needs to be on your form not your button.
HTML
<form action="m.php" method="post" id="form" onsubmit="validateform()">
<input name="submit" type='submit' value='Submit' >
Don't need to validate twice.
JS:
function isEmpty(input) {
return $.trim(input.value) == "";
}
function validateform() {
var user = document.getElementById('u');
var email = document.getElementById('em');
var pass1 = document.getElementById('p1');
var pass2 = document.getElementById('pa2');
if(isEmpty(user) || isEmpty(email) || isEmpty(pass1) || isEmpty(pass2))
alert("All fields are required.");
if(isEmpty(user)){
user.focus();
return false;
}else if(isEmpty(email)){
email.focus();
return false;
}else if(isEmpty(pass1)){
pass1.focus();
return false;
}else if(isEmpty(pass2)){
pass2.focus();
return false;
}
return true;
}
$('form#myForm').submit(function(e){
e.preventDefault();
if( validateform() ) //just validate once!
this.submit(); //and then submit once;
return false;
});
HTML:
<form action="m.php" method="post" id="myForm">
.....
......Other form settings....
.....
<input name="submit" type='submit' value='Submit'>
</form>

Javascript validation not working?

What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.

JavaScript validation for multiple functions?

I have a JavaScript function for a form. The code is :
<script type="text/javascript">
function verify() {
if (isNaN(document.form1.exp_amount.value) == true) {
alert("Invalid Block Amount");
return false;
} else if ((document.form1.exp_name.value).length == 0) {
alert("Block Exp is left Blank!");
return false;
} else if ((document.form1.exp_amount.value).length == 0) {
alert("Block Amount is left Blank!");
return false;
} else {
document.form1.submit();
return true;
}
}
</script>
Now I have to provide Alphabet Validation for it, which I have it in a separate JS function:
<script language="javascript" >
function checkName() {
re = /^[A-Za-z]+$/;
if (re.test(document.exp_name.form1.value)) {
alert('Valid Name.');
} else {
alert('Invalid Name.');
}
}
</script>
If I want to have Alphabet validation inside function verify(), how could I do it? Are there any other ways?
Please change your validation and form to this which will allow submission of the form if valid and not if errors. The following code is in my opinion canonical and will work on all browsers that support regular expressions (which was introduced in JS1.1 in 1996 with NS3.0) - please note that javascript does not support dashes in names unless you quote the field name in the script. The code does not need the form to be named since it passes the form object in the call (this) and uses the object in the function as theForm
<html>
<head>
<title>Canonical forms validation without jQuery</title>
<script type="text/javascript">
var validName = /^[A-Za-z]+$/;
function checkName(str) {
return validName.test(str);
}
function verify(theForm) {
// note: theForm["..."] is short for theForm.elements["..."];
var amount = theForm["exp_amount"].value;
if(amount ==""){
alert("Block Amount is left blank");
theForm["exp_amount"].focus();
return false;
}
if (isNaN(amount)) {
alert("Invalid Block Amount");
theForm["exp_amount"].focus();
return false;
}
var name = theForm["exp_name"].value;
if(name.length==0) {
alert("Block Exp is left Blank!");
theForm["exp_name"].focus();
return false;
}
if(!checkName(name)) {
alert("Block Exp is invalid!");
theForm["exp_name"].focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return verify(this)">
Amount: <input type="text" name="exp_amount" value="" /><br />
Name: <input type="text" name="exp_name" value="" /><br />
<input type="submit" />
</form>
</body>
</html>
Simply return false or true inside your checkName function:
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
false;
}
}
Then call it and check the result.
...
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if (!checkName()) {
return false;
}
else
{
document.form1.submit();
return true;
}
As an aside, there are many ways your code can be cleaned up and improved. I don't want to get into them now, but if you'd like to discuss it, just leave a comment.
Edit your checkName() function to
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
return false;
}
}
And add
else if(!checkName()){ return false;}
to your validation code just before the form submit
<script type="text/javascript">
function verify()
{
if(isNaN(document.form1.exp_amount.value)==true)
{
alert("Invalid Block Amount");
return false;
}
else if((document.form1.exp_name.value).length==0)
{
alert("Block Exp is left Blank!");
return false;
}
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if(!(/^[A-Za-z]+$/.test(document.form1.exp_amount.value))) //ADD THIS
{
alert('Invalid Name');
return false;
}
document.form1.submit();
return true;
}
</script>

Categories

Resources