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';
}
Related
I currently have this code https://codepen.io/jammydodger29/pen/RwgaVom where the user inputs their details into the fields and depending if its valid or not the background of the input will change. I am currently having a problem with my card field. The alert will trigger if the card isn't valid telling the user that the card details is wrong but it won't change the colour to pink, constantly remaining green (as if its valid). In addition, after clicking ok on the alert, I can still submit the form even if the card field is still incorrect. The code for this is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="
// save input string and strip out non-numbers
cc_number_saved = this.value;
this.value = this.value.replace(/[^\d]/g, '');
if(!checkLuhn(this.value)) {
alert('Sorry, that is not a valid number - please try again!');
}"
" onfocus="
// restore saved string
if(this.value != cc_number_saved) this.value = cc_number_saved;
"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
Any help with this would be really appreciated.
I don't know what a valid number input looks like so I will leave checking of that part to you. I extracted your inline js to external js file because such a big amount of inline js hinders readability. Aside from that, you can use formDOM.checkValidity() to check if all the fields of a form are valid and
you can also use field.setCustomValidity() to set a field to invalid.
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
}
mythis.setCustomValidity("Invalid field");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
I currently have this code:
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
}
mythis.setCustomValidity("Invalid field");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
Currently this code will turn any card input details to red regardless if they are valid (I was previously having problems as detailed here Changing Input background colour on invalid. However I know that 4111-1111-1111-1111 for example is a valid card number yet the input field will turn red and not allow me to submit the form. My question is how would I go about changing my current code to allow 4111-1111-1111-1111 as well as other valid card numbers to be accepted?
You need to make sure you only set setCustomValidity if it is really invalid, and if not set it back to blank string
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
return;// make sure you return here!!
}
mythis.setCustomValidity("");
}
Working example:
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
return;
}
mythis.setCustomValidity("");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
I changed your condition in checkLuhn function to make sure that when it is true it shows green, else it is red:
if(checkLuhn(mythis.value)) {
mythis.setCustomValidity('');
}
else{
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
}
This is what you mostly forgot: mythis.setCustomValidity(''); to make sure it is valid
DEMO
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(checkLuhn(mythis.value)) {
mythis.setCustomValidity('');
}
else{
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
}
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
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'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