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"/>
Related
I am fairly new to coding so forgive me if it is something simple I am missing.
I am trying to validate the First Name field using a simple If statement in the function, but when I test it via live server the form submits without throwing the alert.
function validateForm() {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
return false;
} else {
return true;
}
};
firstNameValid(firstName);
};
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname" onsubmit="return firstNameValid(document.registration.fname)"><br>
</li>
<li>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="lname"><br>
</li>
<li>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
<script>
src = "app.js"
</script>
</body>
</html>
The script should be loaded into the page like this…
<script src="app.js"></script>
…not like this…
<script>
src = "app.js"
</script>
validateForm doesn't return anything - you probably just need to change
firstNameValid(firstName);
to
return firstNameValid(firstName);
But, I'm a little rusty on when a form does / does not end up submitting, you may need to do
function validateForm(e) {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
e.preventDefault();
return false;
} else {
return true;
}
};
return firstNameValid(firstName);
};
<form name="registration" action="page2.html" onsubmit="return validateForm(event)" method="GET">
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 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>
I'm trying to have a form where I can search a database, but also have simple error handling where I can check if the user did not enter anything and run the function validateForm. However I'm not sure how to do both.
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
Here's the script
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == null) {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
Instead of "null" in if condition simply use empty string like "".
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == "") {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
</body>
</html>
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();
}
});
});