Im not really sure what Im doing wrong here. I essentially check if any of the elements values are empty, and if they are it started to iterate through them.
Once it iterates it appends the id's of the elements that are empty into the div. Or at least thats what I expected it to do. Any help? Thanks!
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++);{
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " array[i].id ";
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You terminated the for loop independently and hence you are getting out of bond index. And also as pointer by 'Xufox' that is literal string.
Find the corrected script below:
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++){
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " " + array[i].id;
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You can greatly simplify your code by doing something like this instead:
function validate() {
const requiredFields = ['username', 'name', 'phone-number', 'email', 'password', 'password-confirmation'];
const missingFields = requiredFields.filter(requiredFieldStr => {
return !document.getElementById(requiredFieldStr).value;
});
const requiredFieldError = document.getElementById('required-field-error');
if (missingFields.length > 0) {
requiredFieldError.textContent =
"The following must not be blank: " + missingFields.join('');
} else requiredFieldError.textContent = '';
}
I don't know your requirement exactly.
But if you use JQuery validation that will simplify the things for you.
Related
I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>
everyone! I'm building form validation in HTML/JavaScript. The Problem is that it always behaves like the fields are filled and colors the textboxes in blue.
var fName = document.getElementById('fName').value;
fName = document.getElementById('fName').focus();
var lName = document.getElementById('lName').value;
function validation()
{
//check empty fields
if (fName == "" || lName == "")
{
document.getElementById('fName').style.backgroundColor = "red";
document.getElementById('lName').style.backgroundColor = "red";
}
else(fName != "" || lName != "")
{
document.getElementById('fName').style.backgroundColor = "blue";
document.getElementById('lName').style.backgroundColor = "blue";
}
return false;
}
The problem is the line: fName = document.getElementById('fName').focus(); fName in that line is assigned as undefined so you should try something like:
var element = document.getElementById('fName');
var fName = element.value;
element.focus();
When you fire an event or perform some action for example, the returning value is undefined so fName != "" is true.
E.g.:
console.log(element.classList.add("mystyle")); //return undefined
Also check that you should put else if() instead of else () full example: https://jsfiddle.net/cmq0x2a6/
I suggest you try this:
fname
<input type="text" id="fName" onfocus="checkIfEmpty(event)">
lname
<input type="text" id="lName" onfocus="checkIfEmpty(event)">
<script>
function checkIfEmpty(event) {
if (event.relatedTarget != null) {
if (event.relatedTarget.value.length == 0) {
event.relatedTarget.style.backgroundColor = "red";
} else event.relatedTarget.style.backgroundColor = "green";
}
}
</script>
It looks like the problem is in this typo --
else(fName != "" || lName != "")
{
// set the color to 'blue'
}
You miss the if, so (fName != "" || lName != "") is just an expression that you evaluate and then immediately execute the code inside the curly braces.
It all runs OK because you placed the opening brace on the next line (it would've thrown a SyntaxError otherwise).
You need to change your code to
else if (fName !== "" || lName !== "") {
// set the style
}
I will like to know how can I display all of my validated errors at once when user submit a form. Until here, it works fine but it shows the errors one by one.
const form = document.getElementsByTagName('form')[0];
let errorMessages = [
"please fill in your name here",
"please, fill in your email correct here",
];
const reg = /^\d+$/;
form.addEventListener('submit', function(e){
if(valName.value !== ''){
valName.nextElementSibling.textContent = '';
valName.className = '';
} else {
e.preventDefault();
valName.nextElementSibling.textContent = errorMessages[0];
valName.className = 'errorborder';
return false;
}
if(valEmail.value.indexOf('#') != -1 && this.value.indexOf('.') != -1){
valEmail.nextElementSibling.textContent = '';
valEmail.className = '';
} else {
e.preventDefault();
valEmail.nextElementSibling.textContent = errorMessages[1];
valEmail.className = 'errorborder';
return false;
}
});
many thanks in advance!
You have to remove your returns - otherwise the code will stop there.
I have also moved codes into functions instead of copying.
const form = document.getElementsByTagName('form')[0];
let errorMessages = [
"please fill in your name here",
"please, fill in your email correct here",
];
const reg = /^\d+$/;
function isEmailValid(email){
return email.indexOf('#') != -1 && email.indexOf('.') != -1;
}
function isNameValid(name){
return name !== ''
}
function setErrorMessage(el, errorMessage){
el.nextElementSibling.textContent = errorMessage;
el.className = 'errorborder';
}
function clearError(el){
el.nextElementSibling.textContent = '';
el.className = '';
}
form.addEventListener('submit', function(e){
var validName = isNameValid(valName.value);
var validEmail = isEmailValid(valEmail.value);
if(!validName){
setErrorMessage(valName, errorMessages[0]);
}else{
clearError(valName);
}
if(!validEmail){
setErrorMessage(valEmail, errorMessages[1]);
}else{
clearError(valEmail);
}
if(!validName || !validEmail) {
e.preventDefault();
return false;
}
})
You can store all the errors in a string variable and display all of them at once.
form.addEventListener('submit', function(e){
var errors = "";
if(valName.value !== ''){
valName.nextElementSibling.textContent = '';
valName.className = '';
}
else{
e.preventDefault();
errors += errorMessages[0];
}
if(valEmail.value.indexOf('#') != -1 && this.value.indexOf('.') != -1){
valEmail.nextElementSibling.textContent = '';
valEmail.className = '';
}else{
e.preventDefault();
errors += errorMessages[1];
}
if(errors !== ""){
valName.className = 'errorborder';
valName.nextElementSibling.textContent = errors.
return false;
}
})
I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}
I have done a test for a gender expression -
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(gender || gender1)
{
}
else
{
errorMsg = errorMsg + "please select your gender\n"
}
}
but I would like to be able to write it so that there is no need for an empty positive outcome like this -
if ((alphabetic.test(fname)== false) || (alphabetic.test(lname)== false))
{
alertmsg = alertmsg + "Name should be in alphabets:" + "\n";
}
I am sorry if I appear to be very stupid, I am a complete beginner. any help would be appreciated, thanks
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(!(gender || gender1))
{
errorMsg = errorMsg + "please select your gender\n"
}
}
If I understand correctly:
if(!gender && !gender1) {
errorMsg = errorMsg + "please select your gender\n"
}
Not really sure what you are trying to do but, try using the logical NOT "!":
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if !(gender || gender1)
{
errorMsg = errorMsg + "please select your gender\n"
}
}