Changing Input background colour on invalid - javascript

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>

Related

Insert text to specific span from in specific case using Javascript

I have in HTML, three input fields and one button.
beneath each input I have a span.
Every click on the button triggers a function in which colors the empty field in red,
How can I insert a text to the span beneath the input in case the empty field?
HTML:
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<div class="container">
<label for="firstName">First Name</label>
<input type="text" name="" id="firstName">
<span ></span>
<label for="lastName">Last Name</label>
<input type="text" name="" id="lastName">
<span ></span>
<label for="email">Email</label>
<input type="email" name="" id="email">
<span></span>
</div>
<button onclick="showError()"> Show</button>
<script src="train.js"></script>
</body>
</html>
JS
function showError() {
const firstNameEl = document.getElementById("firstName");
const lastNameEl = document.getElementById("lastName");
const emailEl = document.getElementById("email");
let rowsAreFilled = true
let arrayOfAllInfo = [firstNameEl, lastNameEl, emailEl]
for (let i = 0; i < arrayOfAllInfo.length; i++) {
if (arrayOfAllInfo[i].value === "") {
arrayOfAllInfo[i].style.background = "red"
rowsAreFilled = false
}
else {
arrayOfAllInfo[i].style.background = ""
}
}
if (rowsAreFilled === true) {
alert("first name: " + arrayOfAllInfo[0].value + "\n" + "last name: " + arrayOfAllInfo[1].value + "\n" + "email: " + arrayOfAllInfo[2].value)
}
}
You can have the browser enforce required fields for you in a <form> element with the required attribute:
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<form class="container">
<label for="firstName">First Name</label>
<input required type="text" name="" id="firstName">
<label for="lastName">Last Name</label>
<input required type="text" name="" id="lastName">
<label for="email">Email</label>
<input required type="email" name="" id="email">
<button> Show</button>
</form>
<script src="train.js"></script>
</body>
You can style the :required and :invalid pseudo classes:
input:required {
placeholder: 'required';
border: 2px solid black;
}
input:invalid:focus {
border: 2px solid red;
background-color: #f004;
}
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<form class="container">
<label for="firstName">First Name</label>
<input required type="text" name="" id="firstName">
<label for="lastName">Last Name</label>
<input required type="text" name="" id="lastName">
<label for="email">Email</label>
<input required type="email" name="" id="email">
<button>Show</button>
</form>
<script src="train.js"></script>
</body>
Ok, so the answers above of the kind people didn't really answer the question, I asked how to add a text to the specific span by JavaScript in case of empty field..
Any, this is the answer I got to:
function showError() {
const firstNameEl = document.getElementById("firstName");
const lastNameEl = document.getElementById("lastName");
const emailEl = document.getElementById("email");
const errorOneSpan = document.getElementById("errorOne");
const errorSecSpan = document.getElementById("errorSec");
const errorthreeSpan = document.getElementById("errorthree");
let rowsAreFilled = true
let arrayOfSpans = [errorOneSpan, errorSecSpan, errorthreeSpan ]
let arrayOfAllInfo = [firstNameEl, lastNameEl, emailEl]
for (let i = 0; i < arrayOfAllInfo.length; i++) {
if (arrayOfAllInfo[i].value === "") {
arrayOfAllInfo[i].style.background = "red"
arrayOfSpans[i].innerText = "Error!"
rowsAreFilled = false
}
else {
arrayOfAllInfo[i].style.background = ""
arrayOfSpans[i].innerText = ""
}
}
if (rowsAreFilled === true) {
alert("first name: " + arrayOfAllInfo[0].value + "\n" + "last name: " + arrayOfAllInfo[1].value + "\n" + "email: " + arrayOfAllInfo[2].value)
}
}

my js validation doesn't work as I would like (regex)

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';
}

How to get input to accept correct value and change colour?

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>

Adding a node to html page with javascript

This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>

Javascript validation not overriding original css form colors

Can anyone see where I could be making a mistake? The form text-box background colors are originally set to grey. If the user makes a mistake I want to turn them yellow with a red border. The function is sort of working, because the form is not going to the server when the form is filled out incorrectly. But the css doesn't change. If I comment out my js call it will post to the server. Here are the snippets:
CSS:
.invalid{
background-color:#ff9;
border: 2px red inset;
}
.reqd{
background-color:#222222;
color:#555555; border-style: solid;
border-color:#555555;
border-width: 1px;
}
HTML:
<!DOCTYPE html>
<?php
// Debug
error_reporting(E_ALL);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/regauth.js"></script>
<title></title>
</head>
<body id="registerBody">
<section id="registerBox">
<form id="registerForm" method="post" action="regauth.php">
<p>Welcome to the atlas registraton! Please fill out the information below.</p>
<br>
<p><label for="firstName">First Name: <input type="text" size="30" id="firstName" name="firstName" class="reqd"></label></p>
<p><label for="lastName">Last Name: <input type="text" size="30" id="lastName" name="lastName" class="reqd"></label></p>
<p><label for="email">Email: <input type="text" size="30" id="email" name="email" class="reqd"></label></p>
<br>
<br>
<p><label for="reqUsername">Username: <input type="text" size="30" id="reqUsername" name="reqUsername" class="reqd"></label></p>
<p><label for="passOne">Password: <input type="password" size="30" id="passOne" name="passOne" class="reqd"></label></p>
<p><label for="passTwo">Confirm Password: <input type="password" size="30" id="passTwo" name="passTwo" class="reqd"></label></p>
<br>
<br>
<p><input type="submit" value="Submit"> <input type="reset" value="Reset Form" class="reset"></p>
</form>
</section>
<script type="text/javascript">
$("#registerBox").css("margin-left", ($(window).width()-425)/2);
$("#registerBox").css("margin-top", ($(document).height()-500)/2);
$('#registerBox').fadeIn(1500);
</script>
</body>
</html>
JS (regauth.js): Courtesy of Tom Negrino, Visual Quickstart Guide: Javascript Eighth Edition
window.onload = initForms;
//Function loops through each form. For each one it adds an event handler to that forms 'onSubmit'.
function initForms() {
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onsubmit = validForm;
}
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i = 0; i < allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for (var j = 0; j < allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch (thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
default:
classBack += thisClass;
}
return classBack;
}
}
}
Move the "invalid" CSS block to after the "reqd" one.
The rules for CSS are that the "last rule wins" (sort-of; it's more complicated but in this case that's the issue).
Even though the "invalid" rules apply to the invalid elements, because the "reqd" rule has a background color and because it comes after the "invalid" rule, that setting applies.

Categories