Hello and thank you for your time.
I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.
// form validation, makes sure that the user inputs the correct data types.
function validateinput(event){
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var message = document.getElementById('message').value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var firstnameFilter = /^([" "a-zA-Z.-])+$/;
var lastnameFilter = /^([" "a-zA-Z.-])+$/;
var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;
if (!emailFilter.test(email)) {
alert('!Enter a email. Or enter a valid email address.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!firstnameFilter.test(firstname)) {
alert('!Enter a first name. Or enter a valid name.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!lastnameFilter.test(lastname)) {
alert('!Enter a last name. Or enter a name., only letters');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!messageFilter.test(message)) {
alert('!Enter a message.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
have also tried other methods thought they do not seem too work on this page but works on others ?
Like changing the var names and id,s in this one i am using on my contact page
function validateinput(event){
var address1 = document.getElementById('address1').value;
var postcode = document.getElementById('postcode').value;
var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;
var formValid = true;
if (!address1Filter.test(address1)) {
alert('!Enter an address. Or enter a valid address., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
if (!postcodeFilter.test(postcode)) {
alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
So what am I doing wrong ?
the html
<!doctype html>
<!-- name: Edwin martin -date: 30/11/2015 -task: a form with split up inputs using the
<fieldset> & <legend> tags -->
<html lang="en">
<head>
<title>contact</title>
<script type="text/javascript" src="scripts/contact2.js"> </script>
<!-- ensures the document is using the correct char set -->
<meta charset="utf-8">
<meta name="description" content="contact page">
<link rel="icon" href="images/fav.png" type="image/png"/>
<!--
The below section looks like a comment, but it's a conditional include statement.
It's ignored by all browsers except IE9. html5shiv is a library that fixes some HTML5
IE bugs.
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- pulls in the styles sheet -->
<link rel="stylesheet" href="styles/indexstyles.css">
</head>
<body onload="main()">
<!-- start of the form, id form sets the position, size, border style and color -->
<div id="form2">
<!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
<div id="head">
<header id="headcolor">
<div id="toplinks">
<ul>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
</ul>
</div> <br>
<br>
</header>
<h1 id="title"> Contact </h1>
<p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
</div>
<div id="map"> </div>
<!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
<form id="payment">
<!-- Contact Information section -->
<fieldset>
<legend> Personal Information </legend>
<p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname" placeholder="enter a first name" class="add1"></p>
<p> <label> Last Name(*): </label> <input type="text" name="last_name" id="lastname" placeholder="enter a last name" class="add1"></p>
<p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
<p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
<p> <label> message(*): </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
</fieldset>
<!-- Submit button -->
<input type="submit" class="submit_button">
<input type="reset" class="reset_button">
</form>
</div>
<script type="text/javascript" src="scripts/contact.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input
//onload callback function
function main() {
console.log("in main function");
var myForm = document.getElementById("payment");
myForm.addEventListener("submit",validateForm);
}
//validate callback function
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment");
if (myForm.first_name.value == "") {
formValid = false;
//display error message
document.getElementById("firstname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.last_name.value == "") {
formValid = false;
//display error message
document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.email.value == "") {
formValid = false;
//display error message
document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.message.value == "") {
formValid = false;
//display error message
document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
}
document.getElementById('payment').addEventListener("submit", validateinput), the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.
document.getElementById('payment').addEventListener("submit", function(event) {
validateinput(event);
});
I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.
<input type="submit" onclick="return validateinput();" class="submit_button">
You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.
Related
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Checklist</title>
<link rel="stylesheet" type="text/css" href="./style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit"
onchange="document.getElementById('formName').submit()">
</div>
<!--<p id="msg"></p> (I tried using this approach and calling the msg within script but I received an error.)-->
</form>
</div>
</body>
<script>
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
var submit = document.getElementById('submit');
var text = document.getElementById('msg');
//My if/else statement alert works perfectly. However, with the presence of const submit, it doesn't work properly (I think it's interfering with my if/else statement). Removing the const submit section allows one to experience the if/else alert statement. The goal of this checklist is to be able to check one or all four checkboxes and have it return the "Enjoy your day" text. However, I would like for that message to cover the screen and be the only thing visible after hitting the submit button. I'm okay with receiving an alert box when it returns false. However, when it returns true, I would like for the message to cover the screen and for the checklist/checkboxes to disappear. I'm not sure where I'm getting my wires crossed.
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
} else {
return true;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
}
</script>
</html>
enter image description here
enter image description here
You are declaring submit twice in the isChecked function. Omit one of the declaration.
Also, you are adding the event listener to the submit button after the return statement, which JS will ignore and won't append any onclick function.
The updated isChecked function should be
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
// Removed the submit variable
var text = document.getElementById('msg');
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
// Returning true after adding the event listener.
return true;
}
Just display the message since it is being called onsubmit
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
if (!workout && !meeting && !lunch && !school) {
alert('Please check a box');
} else {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
}
return false;
}
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit">
</div>
</form>
</div>
I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.
I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.
In HTML5 in Used this code, i want user to be able to add multiple email address in input box...
<div class="modal-body row-fluid" align="left">
<span class="loader-gif" style="display:none;"><img src="<?php echo $baseURL?>/watever/img/ajax-loader-horizontal.gif"></span>
Email:
<input type="email" multiple="multiple" autofocus="" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" style="display:none;width:91%;cursor:text;" />Links:
<input type="text" readonly="readonly" style="display:none;width:91%;cursor:text;" />
<span class="message" style="display:none;"></span>
</div>
I have added Multiple property in input type="email", still i am not able to add more than one email address in my browser,
i am using, firefox latest version for testing. I just want to know, what is the way, to allow user to add multiple email addresses in that input box?
and how to later retrieve those values using Javascript.
try this, include the jquery and validate js file as per your file location
<html>
<head>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
jQuery.validator.addMethod("multiemail", function (value, element) {
if (this.optional(element)) {
return true;
}
var emails = value.split(','),
valid = true;
for (var i = 0, limit = emails.length; i < limit; i++) {
value = emails[i];
valid = valid && jQuery.validator.methods.email.call(this, value, element);
}
return valid;
}, "Please separate email addresses with a comma and do not use spaces.");
$("#emailFrm").validate({
errorElement:'div',
rules: {
emails: {
required: true,
multiemail:true
}
},
messages:
{
emails: {
required:"Please enter email address."
}
}
});
});
</script>
</head>
<body>
<form method="post" id="emailFrm">
<input type="text" name="emails" />
<input type="submit" name="submit" value="submit">
</form>
</body>
demo click here
Do not use the pattern attribute for e-mail validation. The browsers validate an e-mail address in an e-mail input field.
Himanshu97, you did not specify how you entered the e-mail addresses. Browsers expect them to be separated by comma, not just space (seems weird for me).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>e-mail addresses</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>e-mail addresses</legend>
<label>e-mail addresses
<!-- use email type to enable browser to validate and display error messages
also browsers can display an optimized "keyboard"
do no use pattern, browsers have a build in pattern -->
<input type="email" name="emailAddress" id="emailAddress" value="e#e"
placeholder="e#e, mail#example.com, mail#example.org" autofocus multiple required>
</label>
<p>is valid: input is <span id="isValid">not</span> valid</p>
<p>splitted input:</p>
<ol id="splittedInput"></ol>
<button type="submit">submit</button>
</fieldset>
</form>
<script>
const MAIL_INPUT = document.getElementById('emailAddress');
const IS_VALID = document.getElementById('isValid');
const SPLITTED_INPUT = document.getElementById('splittedInput');
MAIL_INPUT.oninput = (input) => {
IS_VALID.innerText = input.srcElement.validity.valid ? '' : 'not';
const SPLITTED = input.srcElement.value.split(',');
let addresses = [];
let list = [];
for (const SPLIT of SPLITTED)
addresses.push(SPLIT.trim());
for (const ADDRESS of addresses.sort())
list.push(newListElement(ADDRESS));
SPLITTED_INPUT.replaceChildren(...list);
}
function newListElement(content) {
let li = document.createElement('li');
li.innerText = content + ' — ' + (validEmailAddress(content) ? 'valid' : 'invalid');
return li;
}
function validEmailAddress(emailaddress) {
// this regex does not validate correctly. Try abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopq#a.aa (invalid)
return /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailaddress);
}
</script>
</body>
</html>
This seems repeated question but please take a look and try to answer.
My javascript validation function is not working.
Javascript code is given below:
<script type="text/javascript">
var ck_name = /^[A-Za-z ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}
(?:\. [a-z]{2})?)$/i
var ck_mobile = /^[0-9]{10}$/;
var ck_address = /^[A-Za-z0-9-,]{40,100}$/;
function validate(myform){
var name = myform.fullname.value;
var email = myform.email.value;
var mobile = myform.mobile.value;
var address = myform.address.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "Enter valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(mobile)) {
errors[errors.length] = "Enter valid 10 digit mobile number .";
}
if (!ck_password.test(address)) {
errors[errors.length] = "You must enter a valid address min 40 char.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valid Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
I have two button 1)submit and 2)cancel
I want when i click submit button,validate function will call and when i click cancel it goes to back to the page.
HTML form
<form action="addorder.php" method="post" enctype="multipart/form-data" name="myform" >
<!-- Form -->
<div class="form">
<?php
if(isset($_SESSION['msg']))
{
?>
<div class="msg msg-ok"><strong><?php echo $_SESSION['msg'];?></strong></div>
<?php } ?>
<label>Full name<span>(Required Field)</span></label>
<input type="text" name="fullname"class="field size1"/>
</p>
<p>
<label>Email<span> (Required Field)</span>
<input type="text" class="field size1" name="email"/>
</label>
</p>
<p>
<label>Mobile<span>(Required Field)</span>
<input type="text" class="field size1" name="mobile"/>
</label>
</p>
<p>
<label>Address<span>(Required Field)</span>
<textarea class="field size1" name="address" rows="3" cols="10"> </textarea>
</label>
</p>
</div>
<!-- End Form -->
<!-- Form Buttons -->
<div class="buttons" >
<input type="submit" name="submit" class="button" value="Submit" onclick="return validate(myform)" />
<input type="submit" name="cancel" class="button" value="Cancel" />
</div>
<!-- End Form Buttons -->
</form>
I tried your code in a jsfiddle, and it wasn't calling validate. Removing most of your javascript and leaving just a basic validate did call validate. So I think your javascript has syntax errors and the form is ignoring it before submitting. So:
Change the cancel button to type=button, so that it doesn't default to submitting the form when you mean to cancel the submission.
Open firebug, or at the very least the javascript console (in some browsers called the 'error console') and look at the errors you get.
Learning how to debug the javascript will help this time and in the future. Javascript can be completely discarded by the browser if there are syntax errors, in which case your form will just submit as though there was no javascript at all.
Don't see that as a suggestion to only submit via javascript, however, as that would prevent users with javascript switched off from being able to use your form. But that cancel-button-that-submits has to go.