I am currently making a website for user validation form using regex. I am trying to add a button where it only appears when all the fields are enetered correctly(so no errors are made) for the user to click when theyre done.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="test.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
// validation script here
const inputs = document.querySelectorAll('input');
const patterns = {
telephone:/^\d{10}$/, //10 digits
username:/^[a-z\d]{5,12}$/i, //5-12 words
password:/^[\w#-]{8,20}$/, //8-20 words
name:/^[A-Za-z-,]{1,20}$/, //1-20 words
email:/^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/
};
//validation function
function validate(field,regex){
if(regex.test(field.value)){
field.className = 'valid';
}else{
field.className = 'invalid';
}
}
inputs.forEach((input) => {
input.addEventListener('keyup',(e) => {
validate(e.target,patterns[e.target.attributes.name.value])
});
});
});
</script>
</head>
<body>
<div class="container-fluid colorOverlay">
<div class="row">
<article>
<h1 class="headerText">Join Us!</h1>
</article>
<video id="video-background" autoplay loop muted>
<source src="goods.mp4" data-src="goods.mp4" type="video/mp4">
</video>
</div>
</div>
<form>
<input type="text" name="name" placeholder="name">
<p>Name must contain only letters and be 1-20 characters</p>
<input type="text" name="username" placeholder="username">
<p>Username must be and contain 5 - 12 characters</p>
<input type="text" name="email" placeholder="email">
<p>Email must be a valid address, e.g. me#mydomain.com</p>
<input type="password" name="password" placeholder="password">
<p>Password must alphanumeric (#, _ and - are also allowed) and be 8 - 20 characters</p>
<input type="text" name="telephone" placeholder="telephone">
<p>Telephone must be a valid telephone number (10 digits)</p>
<!-- Button -->
<input type="submit" name="register" value="Register" class="btn">
</form>
</body>
</html>
I am still new to javascript and this is just one my personal projects which I'm currently doing. In case you are wondering, The video tag is just for the background.
Here is a complete code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div class="container-fluid colorOverlay">
<div class="row">
<article>
<h1 class="headerText">Join Us!</h1>
</article>
<video id="video-background" autoplay loop muted>
<source src="goods.mp4" data-src="goods.mp4" type="video/mp4">
</video>
</div>
</div>
<form>
<input class="validate" type="text" name="name" placeholder="name">
<p>Name must contain only letters and be 1-20 characters</p>
<input class="validate" type="text" name="username" placeholder="username">
<p>Username must be and contain 5 - 12 characters</p>
<input class="validate" type="text" name="email" placeholder="email">
<p>Email must be a valid address, e.g. me#mydomain.com</p>
<input class="validate" type="password" name="password" placeholder="password">
<p>Password must alphanumeric (#, _ and - are also allowed) and be 8 - 20 characters</p>
<input class="validate" type="text" name="telephone" placeholder="telephone">
<p>Telephone must be a valid telephone number (10 digits)</p>
<!-- Button -->
<input type="submit" name="register" value="Register" id="submit" class="btn">
</form>
<script type = "text/javascript" language = "javascript">
var fields = document.getElementsByClassName("validate");
var submit_button = document.getElementById("submit");
const rules = {
telephone:/^\d{10}$/, //10 digits
username:/^[a-z\d]{5,12}$/i, //5-12 words
password:/^[\w#-]{8,20}$/, //8-20 words
name:/^[A-Za-z-,]{1,20}$/, //1-20 words
email:/^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/
};
var field_status = Array(fields.length);
function validate(field, field_id){
field_status[field_id] = field.value.match(rules[field.name]);
field.className = field.className.replace(/ (in|)valid/, "");
if (!field_status[field_id]){
field.className += " invalid";
} else {
field.className += " valid";
}
toggleSubmitButton();
}
function toggleSubmitButton(){
var status = 0;
for (var x = 0; x < field_status.length; x++){
if (!field_status[x]){
status = 0;
break;
} else {
status = field_status[x];
}
}
var display = "none";
if (status){
display = "block";
}
submit_button.style.display = display;
}
function addKeyUpEvent(field, field_id){
field.addEventListener("keyup", function(event){
validate(this, field_id);
});
}
for (var x = 0; x < fields.length; x++){
addKeyUpEvent(fields[x], x);
}
toggleSubmitButton();
</script>
</body>
</html>
Check validatie of the form after each validation check. A working example based on your input below:
$(document).ready(function() {
// validation script here
const inputs = document.querySelectorAll('input');
const form = document.querySelector('form');
const patterns = {
telephone:/^\d{10}$/, //10 digits
username:/^[a-z\d]{5,12}$/i, //5-12 words
password:/^[\w#-]{8,20}$/, //8-20 words
name:/^[A-Za-z-,]{1,20}$/, //1-20 words
email:/^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/
};
function checkFormValid() {
var isValid = true;
inputs.forEach((input) => {if(input.classList.contains('invalid')) {
isValid = false;
}});
if(!isValid) {
form.classList.add('invalid');
} else {
form.classList.remove('invalid');
}
}
//validation function
function validate(field,regex){
if(regex.test(field.value)){
field.className = 'valid';
} else{
field.className = 'invalid';
}
checkFormValid();
}
inputs.forEach((input) => {
input.addEventListener('keyup',(e) => {
validate(e.target,patterns[e.target.attributes.name.value])
});
});
});
input.valid {
background-color: green;
}
input.invalid {
background-color: red;
}
form [type=submit] {
display: block;
}
form.invalid [type=submit] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="name" placeholder="name">
<p>Name must contain only letters and be 1-20 characters</p>
<input type="text" name="username" placeholder="username">
<p>Username must be and contain 5 - 12 characters</p>
<input type="text" name="email" placeholder="email">
<p>Email must be a valid address, e.g. me#mydomain.com</p>
<input type="password" name="password" placeholder="password">
<p>Password must alphanumeric (#, _ and - are also allowed) and be 8 - 20 characters</p>
<input type="text" name="telephone" placeholder="telephone">
<p>Telephone must be a valid telephone number (10 digits)</p>
<!-- Button -->
<input type="submit" name="register" value="Register" class="btn">
</form>
Related
Why my form is getting submitted even if I leave all fields empty. I can't figure out what the problem is. The if loops looks fine to me.
This is my code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Javascript form check</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body style="margin-top: 30px; margin-left: 30px;">
<form method="POST" action="form-handler" onsubmit="return checkForm(this);">
<p>First Name <input type="text" size="32" name="first_name"></p>
<p>Email Address <input type="text" size="32" name="email"></p>
<p>Phone Number <input type="number" size="32" name="phoneno"></p>
<p>Password <input type="password" size="32" name="pass"></p>
<p>Verify Password <input type="password" size="32" name="pass_verify"></p>
<p>Date of Birth <input type="date" size="32" name="date"></p>
<p>Weight <input type="text" size="32" name="weight"></p>
<input type="submit">
</form>
<script>
function checkForm(form) {
// validation fails if the input is blank
if (form.first_name.value == "") {
alert("Error: Input is empty!");
form.first_name.focus();
return false;
}
if (form.weight.length == 0)
{
alert("Invalid Weight");
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if (!re.test(form.first_name.value)) {
alert("Error: Input contains invalid characters!");
form.first_name.focus();
return false;
}
//Code to Validate Phone Number
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!(form.phoneno.match(phoneno))
{
alert("Number must be 10 characters");
return false;
}
//Code to validate password
var passw= /^[A-Za-z]\w{4,14}$/;
if(!(form.pass.match(passw)))
{
alert('Wrong password')
return false;
}
//Code to validate email
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))){
alert("You have entered an invalid email address!")
return false;
}
}
</script>
</body>
</html>
you are missing a ) in this line
if(!(form.phoneno.match(phoneno)))
Your code was just riddled with errors so I've sorted most of them here :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Javascript form check</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body style="margin-top: 30px; margin-left: 30px;">
<form method="POST" action="form-handler" onsubmit="return checkForm(this);" >
<p>First Name <input type="text" size="32" name="first_name"></p>
<p>Email Address <input type="text" size="32" name="email"></p>
<p>Phone Number <input type="number" size="32" name="phoneno"></p>
<p>Password <input type="password" size="32" name="pass"></p>
<p>Verify Password <input type="password" size="32" name="pass_verify"></p>
<p>Date of Birth <input type="date" size="32" name="date"></p>
<p>Weight <input type="text" size="32" name="weight"></p>
<input type="submit">
</form>
<script>
function checkForm(form) {
// validation fails if the input is blank
if (form.first_name.value === "") {
alert("Error: Input is empty!");
form.first_name.focus();
return false;
}
if (form.weight.length === 0) {
alert("Invalid Weight");
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if (!re.test(form.first_name.value)) {
alert("Error: Input contains invalid characters!");
form.first_name.focus();
return false;
}
//Code to Validate Phone Number
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!(form.phoneno.match(phoneno))) {
alert("Number must be 10 characters");
return false;
}
//Code to validate password
var passw = /^[A-Za-z]\w{4,14}$/;
if (!(form.pass.match(passw))) {
alert('Wrong password')
return false;
}
//Code to validate email
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))) {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
</body>
</html>
Working fiddle here : https://jsfiddle.net/chj8rpxv/1/
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post" required>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</body>
I am creating a library management system and I can't validate the HTML(To add a book copy to the library) with javaScript. I will be uploading the HTML and JS files. When I click on submit I am redirected to the librarian's dashboard. It would be a great help if you could help out with the code.
var btnSubmit = document.getElementById("btn-submit");
btnSubmit.addEventListener("click", function(e) {
e.preventDefault();
validate(e);
});
function validate(e) {
var numbers = /[^0-9]/;
var isbn = document.getElementById("isbn").value;
var copies = document.getElementById("copies").value;
if (isbn.length != 13) {
alert("Please enter a valid ISBN Number");
} else if (isbn.match(numbers)) {
alert("Please enter a valid ISBN Number");
} else if (copies == "") {
alert("Please fill in the number of copies");
} else if (copies.match(numbers)) {
alert("Please enter a valid number of copies");
}
}
<!doctype html>
<html>
<head>
<title>Add Book Copy</title>
<link rel="stylesheet" href="../fonts/fonts.css" />
<link rel="stylesheet" href="../style/style.css" />
<link rel="stylesheet" href="../style/librarian.css">
<link rel="stylesheet" href="../style/add_book.css">
</head>
<body>
<header>
<h2>Librarian</h2>
<form action="../admin/logout.php" method="post">
<input type="submit" id="btn-logout" value="Logout">
</form>
<br style="clear: both" />
</header>
<form action="../admin/add_book_copy.php" method="post">
<h2>Add Book Copy</h2>
<input type="text" name="copyId" placeholder="Book Copy Id" />
<input type="text" name="isbn" placeholder="ISBN" />
<input type="text" name="date" id="date" hidden />
<input type="submit" value="submit" id="btn-submit" />
</form>
<script src="../js/add_book_copy.js"> </script>
</body>
</html>
You have not given id to your input's i.e : isbn and copies that's the reason it is not working .I have given id to input boxes .i.e :
var btnSubmit = document.getElementById("btn-submit");
btnSubmit.addEventListener("click", function(e) {
e.preventDefault();
validate(e);
});
function validate(e) {
var numbers = /[^0-9]/;
//you are getting values by using id give input id attribute as well
var isbn = document.getElementById("isbn").value;
var copies = document.getElementById("copies").value;
if (isbn.length != 13) {
alert("Please enter a valid ISBN Number");
} else if (isbn.match(numbers)) {
alert("Please enter a valid ISBN Number");
}
if (copies == "") {
alert("Please fill in the number of copies");
}
else if (copies.match(numbers)) {
alert("Please enter a valid number of copies");
}
}
<!doctype html>
<html>
<head>
<title>Add Book Copy</title>
<link rel="stylesheet" href="../fonts/fonts.css" />
<link rel="stylesheet" href="../style/style.css" />
<link rel="stylesheet" href="../style/librarian.css">
<link rel="stylesheet" href="../style/add_book.css">
</head>
<body>
<header>
<h2>Librarian</h2>
<form action="../admin/logout.php" method="post">
<input type="submit" id="btn-logout" value="Logout">
</form>
<br style="clear: both" />
</header>
<form action="../admin/add_book_copy.php" method="post">
<h2>Add Book Copy</h2>
<!--added id-->
<input type="text" name="copyId" id="copies" placeholder="Book Copy Id" />
<input type="text" name="isbn" id="isbn" placeholder="ISBN" />
<input type="text" name="date" id="date" hidden />
<input type="submit" value="submit" id="btn-submit" />
</form>
<script src="../js/add_book_copy.js"> </script>
</body>
</html>
You can simply add the pattern attribute in the input tag
<input type="text" name="copyId" placeholder="Book Copy Id" pattern="[0-9]+" />
<input type="text" name="isbn" placeholder="ISBN" pattern="[0-9]{13}"/>
<input type="text" name="date" id="date" hidden />
<input type="submit" value="submit" id="btn-submit" />
With the help of this , you will not need the javascript function .
You did not give id to <input>:
<input type="text" name="copyId" placeholder="Book Copy Id" id="copies"/>
<input type="text" name="isbn" placeholder="ISBN" id="isbn"/>
Working on a simple registration form in Javascript and I can't quite figure out why my phone validation function isn't working. What I'm trying to do is
Make the field optional. If the user doesn't put anything in the field, the form will still be valid and submit
If the user puts in a phone number, it must be in an XXX-XXX-XXXX format.
Any and all help is appreciated.
Here is my code
function validateform() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var dob = document.getElementById('dob');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
if (username.value.length < 8) {
alert("Username must be at least 8 characters");
username.focus();
return false;
}
if (password.value.length < 8) {
alert("Password must be at least 8 characters");
password.focus();
return false;
}
let isVaild = moment(dob.value, 'MM/DD/YYYY', true).isValid()
if (!isVaild) {
alert("Date must be in MM/DD/YYYY format");
dob.focus();
return false;
}
}
function validatePhone() {
var num1 = document.getElementById('phone').value;
if (num1 !== "" && !num1.match(/\(\d{2}\)\d{8}/)) {
alert('That is not a correct telephone number format');
return false;
}
}
function vailddatecheck(dateString) {
var dateforvailidation = dateString.value;
var isVaild = moment(dateforvailidation, 'MM/DD/YYYY', true).isVaild();
if (isVaild) {
return true;
} else {
alert("Date must be in MM/DD/YYYY format");
form.dob.focus();
return false;
}
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Totally Legit Registration Page</title>
<link href="Mod4style.css" rel="stylesheet">
</head>
<body>
<form class="submit.html" method="post" class="simpleForm" onsubmit="return validateform()">
<input type="text" id="username" placeholder="User Name">
<p class="error"></p>
<input type="password" id="password" placeholder="Password">
<p class="error"></p>
<input type="firstname" id="firstname" placeholder="First Name">
<p class="error"></p>
<input type="lastname" id="lastname" placeholder="Last Name">
<p class="error"></p>
<input type="dob" id="dob" placeholder="Date of Birth">
<p class="error"></p>
<input type="email" id="email" placeholder="Email">
<p class="error"></p>
<input type="phone" id="phone" placeholder="Phone Number" onsubmit="return validatePhone();">
<p class="error"></p>
<button type="Submit" onClick="">Submit</button>
<button type="Reset">Reset</button>
</form>
<script <script src="formvalidation.js" charset="utf-8"></script>
</body>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
</html>
The function validate validatePhone() will never be called due to
<input type="phone" id="phone" placeholder="Phone Number" onsubmit="return validatePhone();">
onsubmit will should be added to <form> and in the end of validateform add
return validatePhone()
And correct regex is following
^(\d{3}-){2}\d{4}$
The last problem is using match() match always return array which is always trucy. Even Boolean([]) will be true. So !num1.match(/\(\d{2}\)\d{8}/ will always be false. You should use RegExp.prototype.test.
if (num1 !== "" && !/(\d{3}-){2}\d{4}/.test(num1))
function validateform() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var dob = document.getElementById('dob');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
if(username.value.length < 8){
alert("Username must be at least 8 characters");
username.focus();
return false;
}
if (password.value.length < 8) {
alert("Password must be at least 8 characters");
password.focus();
return false;
}
let isVaild = moment(dob.value, 'MM/DD/YYYY', true).isValid()
if (!isVaild)
{
alert("Date must be in MM/DD/YYYY format");
dob.focus();
return false;
}
return validatePhone();
}
function validatePhone()
{
console.log('x')
var num1 = document.getElementById('phone').value;
if (num1 !== "" && !/(\d{3}-){2}\d{4}/.test(num1))
{
alert('That is not a correct telephone number format');
return false;
}
}
function vailddatecheck(dateString) {
var dateforvailidation = dateString.value;
var isVaild = moment(dateforvailidation, 'MM/DD/YYYY' , true).isVaild();
if (isVaild) {
return true;
}
else {
alert("Date must be in MM/DD/YYYY format");
form.dob.focus();
return false;
}
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Totally Legit Registration Page</title>
<link href="Mod4style.css" rel="stylesheet">
</head>
<body>
<form class="submit.html" method="post" class="simpleForm" onsubmit="return validateform()">
<input type="text" id="username" placeholder="User Name">
<p class="error"></p>
<input type="password" id="password" placeholder="Password">
<p class="error"></p>
<input type="firstname" id="firstname" placeholder="First Name">
<p class="error"></p>
<input type="lastname" id="lastname" placeholder="Last Name">
<p class="error"></p>
<input type="dob" id="dob" placeholder="Date of Birth" >
<p class="error"></p>
<input type="email" id="email" placeholder="Email">
<p class="error"></p>
<input type="phone" id="phone" placeholder="Phone Number">
<p class="error"></p>
<button type="Submit" onClick="">Submit</button>
<button type="Reset">Reset</button>
</form>
<script <script src="formvalidation.js" charset="utf-8"></script>
</body>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
</html>
Your regex is incorrect. Try /^\d{3}-\d{3}-\d{4}$/.
The regex you provided will match any number of the format (##)########
function validateform() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var dob = document.getElementById('dob');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
if (username.value.length < 8) {
alert("Username must be at least 8 characters");
username.focus();
return false;
}
if (password.value.length < 8) {
alert("Password must be at least 8 characters");
password.focus();
return false;
}
let isVaild = moment(dob.value, 'MM/DD/YYYY', true).isValid()
if (!isVaild) {
alert("Date must be in MM/DD/YYYY format");
dob.focus();
return false;
}
}
function validatePhone() {
var num1 = document.getElementById('phone').value;
if (num1 !== "" || !num1.match(/\(\d{2}\)\d{8}/)) {
alert('That is not a correct telephone number format');
return false;
}
}
function vailddatecheck(dateString) {
var dateforvailidation = dateString.value;
var isVaild = moment(dateforvailidation, 'MM/DD/YYYY', true).isVaild();
if (isVaild) {
return true;
} else {
alert("Date must be in MM/DD/YYYY format");
form.dob.focus();
return false;
}
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Totally Legit Registration Page</title>
<link href="Mod4style.css" rel="stylesheet">
</head>
<body>
<form class="submit.html" method="post" class="simpleForm" onsubmit="return validateform()">
<input type="text" id="username" placeholder="User Name">
<p class="error"></p>
<input type="password" id="password" placeholder="Password">
<p class="error"></p>
<input type="firstname" id="firstname" placeholder="First Name">
<p class="error"></p>
<input type="lastname" id="lastname" placeholder="Last Name">
<p class="error"></p>
<input type="dob" id="dob" placeholder="Date of Birth">
<p class="error"></p>
<input type="email" id="email" placeholder="Email">
<p class="error"></p>
<input type="phone" id="phone" placeholder="Phone Number" onsubmit="return validatePhone();">
<p class="error"></p>
<button type="Submit" onClick="">Submit</button>
<button type="Reset">Reset</button>
</form>
<script <script src="formvalidation.js" charset="utf-8"></script>
</body>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
</html>
This question already has answers here:
What is the meaning of onsubmit="return false"? (JavaScript, jQuery)
(4 answers)
Closed 5 years ago.
I have this HTML project that validates an empty form. The error is being displayed on the side of the inputs but only flashes for a second. I just want the error of the messages to be displayed once
This is my HTML code with the necessary links:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - JQuery </title>
<link rel="stylesheet" type="text/css" href="contactform.css">
</head>
<body>
<h1 id="pageheading">Zedland Health Authority</h1>
<h2 class="sectionheading">Contact Form</h2>
<form id="register">
<fieldset id="controls">
<div>
<label class="formlabel" for="fname">First Name: </label>
<input id="fname" type="text" size="30" placeholder="First name"
autofocus>
<p id="fname-error" class="error" style="display:none; color:red;">*
You must enter a first name.</p>
</div>
<div>
<label class="formlabel"for="lname">Last Name: </label>
<input id="lname" type="text" size="30">
<p id="lname-error" class="error" style="display:none; color:red;">*
You must enter a Last name.</p>
</div>
<div>
<label class="formlabel" for="title">Title: </label>
<select id="title">
<option value="Mr">Mr.</option>
<option value="Ms">Ms.</option>
<option value="Mrs">Mrs.</option>
<option value="Miss">Miss.</option>
<option value="Master">Master.</option>
</select>
</div>
<div>
<label class="formlabel" for="heathauthoritynumber"><span>
<img src="tooltip.png" id="qmark" alt="Hint"></span>
Health Authority Number:
</label>
<input id="healthauthoritynumber" type="text" size="10">
<p id="hn-error" class="error" style="display:none; color:red;">*You
must enter a Health Authority Number eg('ZHA345742)</p>
<div class="tooltip" id="ttip">If you do not know your ZHA number
,please contact your GP</div>
</div>
<div>
<label class="formlabel" for="email">Email: </label>
<input id="email" type="text" size="40">
<p id="email-error" class="error" style="display:none; color:red;">You
must enter email</p>
</div>
<div>
<label class="formlabel" for="telephone">Telephone Number: </label>
<input id="telephone" type="text" size="40">
<p id="tele-error" class="error" style="display:none; color:red;">You
must enter a telephone</p>
</div>
<div class="formlabel">
<input id="submit-button" type="submit" value="Submit" >
</div>
</fieldset>
</form>
<script src="contactform.js"></script>
</body>
</html>
This is my Javascript
function onSubmit(){
console.log("ive been submitted");
checkEmpty(document.getElementById('fname'),document.getElementById("fname-error"));
checkEmpty(document.getElementById('lname'),document.getElementById("lname-error"));
checkEmpty(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
checkEmpty(document.getElementById('email'),document.getElementById("email-error"));
checkEmpty(document.getElementById('telephone'),document.getElementById("tele-error"));
//checkValidHealthID(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
}
// Read about regular expressions using: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
// and http://stackoverflow.com/questions/25155970/validating-uk-phone-number-regex-c
function checkValidHealthID(inputID, errorID){
var re = new RegExp('/ZHA\d{6}$/');
if((inputID.value)!== re){
errorID.style.display = "inline";
}else
{
errorID.style.display = "none";
}
}
function checkEmpty(inputID, errorID){
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
console.log("checking empty");
if((inputID.value === "") || (inputID.value.length === 0)){
console.log("empty!!");
errorID.style.display = "inline";
}
else
{
errorID.style.display = "none";
}
}
function textHint(txtElem, defaultText) {
txtElem.value = defaultText;
txtElem.style.color = "#A8A8A8";
txtElem.style.fontStyle = "italic";
txtElem.onfocus = function() {
if (this.value === defaultText) {
this.value = "";
this.style.color = "#000";
this.style.fontStyle = "normal";
}
}
txtElem.onblur = function() {
if (this.value === "") {
this.value = defaultText;
this.style.color = "#A8A8A8";
this.style.fontStyle = "italic";
}
}
}
function textHints() {
//textHint(document.getElementById("firstName"), "Enter your first name");
textHint(document.getElementById('lname'), "Enter your last name");
textHint(document.getElementById('healthauthoritynumber'), "for eg
,ZHA346783");
textHint(document.getElementById('email'), "Enter your email");
textHint(document.getElementById('telephone'), "Enter your telephone
number");
}
function switchToolTip() {
document.getElementById('qmark').onmouseover = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='block';
}
document.getElementById('qmark').onmouseout = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='none';
}
}
//windows.onload=textHints();
//windows.onload=switchToolTip();
//window.onload=init;
document.getElementById("submit-button").onclick = onSubmit;
Your form is getting submitted which results in page reload. That's why you see the message flashing for a while. I saw the commented line in your JavaScript
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
You should get uncomment e.preventDefault().
Grab the click event as function onSubmit(event) and pass the event to checkEmpty.
my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});