I'm creating a registration page and am currently attempting to store the inputs of the form into an array. I'm using
var form_inputs = document.getElementsByClassName("form_input");
to store the inputs in the same place, however if I try to alert form_inputs to test if anything is actually being stored, it just alerts "Undefined".
function validate_form(event) {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var form_inputs = document.getElementsByClassName("form_input");
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly");
console.log(form_inputs);
event.preventDefault(); // Prevent the form from submitting
}
if (!email.value.includes("#") || !email.value.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input class="form_input" type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input class="form_input" type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input class="form_input" type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input class="form_input" type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input class="form_input" type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input class="form_input" type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form(event)" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
Array.from(document.getElementsByClassName("form_input")).forEach(
function(element, index, array) {
alert(element.innerHTML)
}
);
this will alert you of those elements
Related
Hi everyone i have question about my code the plan was that the script was supposed to display message if someone did not enter anything in input or enter somethink thats did not match to my pattern (but if someone lift message will disappear [this doesnt work]) and i dont know where is problem and how to fix it
here is my code:
html
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="odp.php" method="post" id="form">
<div>
<label for="imie">Imie</label>
<input type="text" name="imie" id="imie" placeholder="Imie" required>
<span></span>
</div>
<div>
<label for="nazwisko">Nazwisko</label>
<input type="text" name="nazwisko" id="nazwisko" placeholder="Nazwisko" required>
<span></span>
</div>
<div>
<label for="pesel">Pesel</label>
<input type="number" placeholder="pesel" name="pesel" id="pesel" required>
<span></span>
</div><br>
adres zamieszkania:
<div>
<label for="kod">kod</label>
<input type="text" name="kod" id="kod" placeholder="kod" required>
<span></span>
</div>
<div>
<label for="miejscowosc">miejscowość</label>
<input type="text" name="miejscowosc" id="miejscowosc" placeholder="Miejscowość" required>
<span></span>
</div>
<div>
<label for="ulica">ulica</label>
<input type="text" name="ulica" id="ulica" placeholder="Ulica" required>
<span></span>
</div>
<div>
<label for="nrdomu">nr domu</label>
<input type="text" name="nrdomu" id="nrdomu" placeholder="nr domu" required>
<span></span>
</div>
<div>
<label for="nrmieszkania">nr mieszkania</label>
<input type="text" name="nrmieszkania" id="nrmieszkania" placeholder="nr mieszkania">
<span></span>
</div><br>
<div>
<label for="emial">Emial</label>
<input type="email" name="email" placeholder="email" id="email" required>
<span></span>
</div>
<div>
<label for="number">Numer Telefonu</label>
<input type="number" name="nrtel" placeholder="Numer-telefonu" id="number" required>
<span></span>
</div>
<input type="submit" id="submit">
</form>
<script src="main.js"></script>
</body>
</html>
and my js
let nazwisko = document.getElementById('nazwisko');
let pesel = document.getElementById('pesel');
let kod = document.getElementById('kod');
let miejscowosc = document.getElementById('miejscowosc');
let ulica = document.getElementById('ulica');
let nrdomu = document.getElementById('nrdomu');
let nrmieszkania = document.getElementById('nrmieszkania');
let email = document.getElementById('email');
let number = document.getElementById('number');
let span = document.getElementsByTagName('span');
let form = document.getElementById('form');
var arr = [imie,nazwisko,pesel,kod,miejscowosc,ulica,nrdomu,nrmieszkania,email,number];
for(let i = 0; i < arr.length; ++i){
var regex;
console.log(arr[i]);
if(i == 0 || i == 1 || i == 4 || i == 5){
regex = /^[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź]{3,100}$|^[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź]+[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź0-9\s\-]+[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź0-9]{1,100}$/;
console.log(arr[i].value.match(regex));
}
if(i == 2){
regex = /^[0-9]{11}$/;
console.log(regex);
}
if(i == 3){
regex = /^[0-9]{2}-[0-9]{3}$/i;
console.log(regex);
}
if(i == 6){
regex = /[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1000/i;
console.log(regex);
}
if(i == 7){
regex = /[0-9]/gm;
console.log(regex);
}
if(i == 8){
regex = /\b[\w\.-]+#[\w\.-]+\.\w{2,4}\b/gi;
console.log(regex);
}
if(i == 9){
regex = /^(?:\+\d\d)?\d{3}(-?)\d{3}\1\d(\d\d)?$/gm;
console.log(regex);
}
arr[i].onblur = function(){
if(arr[i].value.match(regex)){
span[i].innerHTML = "";
}else{
span[i].innerHTML = "Uzupełnij " + arr[i].name;
span[i].style.color = 'red';
}
}
if(i == 7){
arr[i].onblur = span[i].innerHTML = "";
}
}```
the <span></span> tags you are using in the Html do not have an id to which your logic can set the value that you define in the JS
else{
span[i].innerHTML = "Uzupełnij " + arr[i].name;
span[i].style.color = 'red';
}
On submitting an empty form I'm receiving the respective errors but I want to remove the error (when they meet the requirement) as I proceed to the next input. Also can anyone give me a solution to do the same with the help of loops. Only JavaScript solution please.
Here's my JS and HTML code..
function validate() {
var letter = /[a-zA-Z]/;
var number = /[1-9]{1}[0-9]{2}/;
var mail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var valid = true;
var firstname = information.first.value;
var lastname = information.last.value;
var address = information.Add.value;
var email = information.Email.value;
var pass = information.Pass.value;
var re_pass = information.Repass.value;
var phone = information.mobile.value;
if (firstname === "" || !letter.test(firstname)) {
document.getElementById("fn").innerHTML = "*Enter your First Name*";
console.log("first");
valid = false;
} else {
document.getElementById("fn").innerHTML = "";
}
if (lastname === "" || !letter.test(lastname)) {
document.getElementById("ln").innerHTML = "*Enter your Last Name*";
console.log("last");
valid = false;
} else {
document.getElementById("ln").innerHTML = "";
}
if (email === "" || !mail.test(email)) {
document.getElementById("mail").innerHTML = "*Enter your Email*";
console.log("mail");
valid = false;
} else {
document.getElementById("mail").innerHTML = "";
}
if (pass === "" || !letter.test(Pass)) {
document.getElementById("pwd").innerHTML = "*Enter your Password*";
console.log("password");
valid = false;
} else {
document.getElementById("pwd").innerHTML = "";
}
if (re_pass === "" || re_pass != pass) {
document.getElementById("repass").innerHTML = "*Password didn't match*";
console.log("reenter");
valid = false;
} else {
document.getElementById("repass").innerHTML = "";
}
if (phone == "" || !number.test(phone)) {
document.getElementById("no").innerHTML = "*Enter your Phone number";
console.log("phone");
valid = false;
} else {
document.getElementById("no").innerHTML = "";
}
return valid;
}
<!DOCTYPE html>
<html>
<head>
<title>information</title>
<link rel="stylesheet" type="text/css" href="info.css">
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="form">
<form action="#" method="POST" onsubmit="return validate()" name="information">
<label>Firstname:</label>
<input type="text" name="firstname" placeholder="Enter your name" id="first" autofocus>
<span id="fn"></span><br><br>
<label>Lastname:</label>
<input type="text" name="lastname" placeholder="Enter last name" id="last">
<span id="ln"></span><br><br>
<label>Address:</label>
<input type="text" name="address" placeholder="Address" id="Add">
<span id="add"></span><br><br>
<label>Email:</label>
<input type="email" name="mail" placeholder="Email" id="Email">
<span id="mail"></span><br><br>
<label>Password:</label>
<input type="password" name="password" placeholder="Password" id="Pass">
<span id="pwd"></span><br><br>
<label>Retype Password:</label>
<input type="password" name="retype" placeholder="Retype password" id="Repass">
<span id="repass"></span><br><br>
<label>Phone:</label>
<input type="text" name="firstname" placeholder="XXXXXXXXXX" id="mobile" maxlength = "10">
<span id="no"></span><br><br>
<input type="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
Perhaps this?
var letter = /[a-zA-Z]/;
var number = /[1-9]{1}[0-9]{2}/;
var mail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
function validate() {
var information = document.querySelector("#form>form");
var error = 0;
var firstname = information.first.value;
var lastname = information.last.value;
var address = information.Add.value;
var email = information.Email.value;
var pass = information.Pass.value;
var re_pass = information.Repass.value;
var phone = information.mobile.value;
error += firstname === "" || !letter.test(firstname)
document.getElementById("fn").innerHTML = error?"*Enter your First Name*":"";
error += lastname === "" || !letter.test(lastname)
document.getElementById("ln").innerHTML = error?"*Enter your Last Name*":"";
error += email === "" || !mail.test(email)
document.getElementById("mail").innerHTML = error?"*Enter your Email*":"";
error += pass === "" || !letter.test(Pass)
document.getElementById("pwd").innerHTML = error?"*Enter your Password*":"";
error += re_pass === "" || re_pass !== pass
document.getElementById("repass").innerHTML = error?"*Password didn't match*":"";
error += phone === "" || !number.test(phone)
document.getElementById("no").innerHTML = error ? "*Enter your Phone number":"";
return error>0?false:true;
}
document.querySelector("#form>form").oninput = validate;
document.querySelector("#form>form").onsubmit = validate;
<div id="form">
<form action="#" method="POST" name="information">
<label>Firstname:</label>
<input type="text" name="firstname" placeholder="Enter your name" id="first" autofocus>
<span id="fn"></span><br><br>
<label>Lastname:</label>
<input type="text" name="lastname" placeholder="Enter last name" id="last">
<span id="ln"></span><br><br>
<label>Address:</label>
<input type="text" name="address" placeholder="Address" id="Add">
<span id="add"></span><br><br>
<label>Email:</label>
<input type="email" name="mail" placeholder="Email" id="Email">
<span id="mail"></span><br><br>
<label>Password:</label>
<input type="password" name="password" placeholder="Password" id="Pass">
<span id="pwd"></span><br><br>
<label>Retype Password:</label>
<input type="password" name="retype" placeholder="Retype password" id="Repass">
<span id="repass"></span><br><br>
<label>Phone:</label>
<input type="text" name="firstname" placeholder="XXXXXXXXXX" id="mobile" maxlength="10">
<span id="no"></span><br><br>
<input type="submit" name="mysubmit" value="submit">
</form>
</div>
I'm currently writing a registration form in HTML and have come across a couple of problems. Firstly, I have to have a separate button outside of the form tags to run the function as my submit button just submits the form whether input fields are entered incorrectly, only showing the validation alerts for a split second. Secondly, if I enter the email correctly it states that 'email.includes' is not valid, however, it still runs as it should, this error does not appear if I enter an invalid email. Thanks for any answers (I know my code is not great, I'm still learning a lot)
function validate_form() {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly")
}
if (!email.value.includes("#") || !email.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form()" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
</html>
Two issues here:
When you don't want to submit your form (e. g. entered details are incorrect), you will need to prevent it from submitting. In JavaScript, you can to this with preventDefault().
So achieve this, I added the line event.preventDefault() to your if statement that checks if there are any errors. Keep in mind that you need to pass the event parameter to your function in order to get preventDefault() working.
Secondly, you need to check if the value of your email field includes something.
You got your email field like this: var email = document.getElementById('email');, so you need to check the value like this: email.value.includes('bla').
All together, your script works perfectly fine:
function validate_form(event) {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly");
event.preventDefault(); // Prevent the form from submitting
}
if (!email.value.includes("#") || !email.value.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form(event)" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
</html>
If there is an validation error you need to prevent the event default behavior in order to prevent the browser from redirecting to target page (what you specified in the action attribute, or reloading the current page if not specified):
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Your second question: I guess its email.value.includes (as you already used in your code on an other point) and you whant to check the value not the HTML-Node itself.
You might also want to look in email regex validation which would match the requirements of an email validation way better than checking for "#" an "." e.g. https://www.w3resource.com/javascript/form/email-validation.php
I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/