I am making a contact form, which includes name, email and a message which can then be submitted. If any of the three fields are null an error message is shown which I have working. The word "error" appears in all three field boxes. My issue is that I am trying to add a single error message which will be hidden and only appear if an error is made, this will say "Please fill in all fields before submitting"
I am new to ColdFusion and mixing HTML with JavaScript. So I was wondering if anyone could please give me some tips as to what I have done wrong. I have tried to manipulate it many ways and tried adding a div for this message in my CSS. But to no avail, the message always shows up. It doesn't stay hidden when needed.
I would really appreciate any information or help anyone could give, I am so confused and have searched the whole web looking for this info.
Here is my code:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "Error";
var emptyFields = true;
}
}
if (!emptyFields) {
myForm.submit();
} else {
if (document.getElementById("name == null || email == null || message == null")
document.getElementById("errormessage").style.visibility = "visible";
} else {
document.getElementById("errormessage").style.visibility = "hidden";
}
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
and here is the CSS for my error message:
#errormessage {
font-style: italic;
text-indent: 10px;
border: dotted;
border-width: 1px;
}
There is a much easier way to do form validation with ColdFusion. If you use <cfform> and <cfinput> tags then a lot of JavaScript is written for you. All you have to do is something like this:
<cfform action="whereever">
<cfinput type="text" name="fred" required="yes" message="fred is required">
<input type="submit">
</cfform>
It's not as fancy as what you are attempting, but it's simple and it's effective.
Please go through the below code and see what you have done wrong.
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body onload="checkContactForm();">
<style type="text/css">
#errormessage {
font-style: italic;
text-indent: 10px;
border: dotted;
border-width: 1px;
}
</style>
<script type="text/javascript">
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "Error";
var emptyFields = true;
}
}
if (!emptyFields) {
myForm.submit();
}
else
{
if (emptyFields) {
document.getElementById("errormessage").innerHTML = "Validation Error";
document.getElementById("errormessage").style.visibility = "visible";
}
else
{
document.getElementById("errormessage").style.visibility = "hidden";
}
}
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
</script>
<div id="errormessage"></div>
<form action="STO1.html" method="POST" name="myForm">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<input type="text" name="message" id="message"/>
<input type="submit"/>
</form>
</body>
</html>
Related
guys I'm new here and it's my first time posting . been learning html / CSS / javascript since 5 months ago and now I'm trying to build a very simple contact form where if there's no value it will show error icon + message error blow the input , been trying to figure it out for like 12h+ but nothing i saw in stack worked ....... already have the solution of a guy , he used javascript to manipulate the style and add and remove the error using css , but i want to do it the other way around with manipulating the DOM with JAVA using document.query Selector
let firstname = document.querySelector("#inputfirst").value;
let form = document.querySelector('#loginform')
//form.addEventListener('submit', (e) => {
// e.preventDefault();})
function validation() {
if (firstname == "" || firstname == null || firstname == " ") {
document.querySelector("#inputfirst").classList.add("firstname")
document.querySelector("#firstname_Error").innerHTML = "firstname"
return false;
}
else {
document.querySelector("#inputfirst").classList.remove("firstname")
document.querySelector("#firstname_Error").innerHTML = ""
}
}
/**testing for 1st input only **/
.firstname {
background-image: url(./images/icon-error.svg);
background-position: 24rem 13px;
background-repeat: no-repeat;
border: 1px solid rgb(247, 10, 10);
}
<form novalidate id="loginform" name="loginform" onsubmit="return validation()"; >
<input id="inputfirst" name="firstname" type="text" placeholder="First Name" class="button-shap" required >
<span id="firstname_Error"></span>
</form>
Get the value of the element inside the function.
Everything else seems to be working.
Here is the edited code.
let firstnameElement = document.querySelector("#inputfirst");
let form = document.querySelector('#loginform')
//form.addEventListener('submit', (e) => {
// e.preventDefault();})
function validation() {
let firstname = firstnameElement.value
if (firstname == "" || firstname == null || firstname == " ") {
document.querySelector("#inputfirst").classList.add("firstname")
document.querySelector("#firstname_Error").innerHTML = "firstname"
return false;
}
else {
document.querySelector("#inputfirst").classList.remove("firstname")
document.querySelector("#firstname_Error").innerHTML = ""
}
}
Also if your javascript file is linked at the head of the html make sure to add the defer attribute so it loads after the document.
<script src="test.js" defer></script>
In process of learning JS. Trying to learn how to loop through an entire form, and have errors pointed out.
This is a hodgepodge that I cobbled together from various tutorials online.
Clearly it's not working.
What I am trying to do is to get the forms' entire collection of its elements, and loop through it, and anything that's blank, to have its error message printed somewhere on the same screen, be it above the form or underneath the textboxes itself.
This is what I have so far. Any help in getting this to work, or at least the concept of what I outlined? Simple and bite-size explanations if possible would be appreciated.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="text" name="Email"></label></p>
<p><input type="submit" value="Submit"></p>
</form>
<script>
var formsCollection = document.forms[0];
for (var i = 0; i < formsCollection.elements.length; i++) {
if (formsCollection.elements.value.length == 0) {
form.elements.input.border = "1px solid red";
form.Name.style.backgroundColor = "#FFCCCC";
}
return true;
}
document.getElementById("myForm").onsubmit = function () {
return Validate(this);
};
</script>
</body>
</html>
EDIT
<script>
function Validate() {
var formsCollection = document.forms[0];
for (var i = 0; i < formsCollection.elements.length; i++) {
if (formsCollection.elements[i].value.length == 0) {
form.elements.input.border = "1px solid red";
form.Name.style.backgroundColor = "#FFCCCC";
}
return true;
}
document.getElementById("myForm").onsubmit = function () {
return Validate(this);
};
}
</script>
Full ans:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="text" name="Email"></label></p>
<p><input type="submit" value="Submit"></p>
</form>
<script>
document.forms[0].onsubmit= function() {
var form = document.forms[0];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value.length == 0) {
console.log(form.elements[i]);
form.elements[i].border = "1px solid red";
form.elements[i].style.backgroundColor = "#FFCCCC";
return false;
}
}
}
</script>
</body>
</html>
Several problems.
There seems to be no i in your for loop usage.
Try if (formsCollection.elements.value.length == 0) {
to if (formsCollection.elements[i].value.length == 0) {
Where is your Validate function?
Wrap var formsCollection ... END_OF_FOR_LOOP with function Validate(){ and }
I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.
I was doing a project series on CodeCademy and I got a project in the series to do a client side form validation using JavaScript/jQuery.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
Age : <input type='text' id='age' placeholder='Age'><br><br>
Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
</form>
<button id='submit'>Submit</button>
</body>
</html>
My JavaScript/jQuery is:
$(document).ready(function()
{
var fname = document.getElementById('fname').val();
var lname = document.getElementById('lname').val();
var age = document.getElementById('age').val();
/*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/
$("#submit").click(function()
{
if(fname.length === 0)
{
alert("Please input a first name");
}
else if(lname.length === 0)
{
alert("Please input a last name");
}
else if(age.length === 0)
{
alert("Please input an age");
}
});
});
I don't need a very complicated code and please help me in the HTML department if something is wrong there or if something needs to be added there.
Also, I don't know how to get different elements in a class. I have put a comment in my jQuery regarding that so please help if you can.
This is a problem in a CodeCademy project and this is where a lot of newbies in JS and jQuery have a problem, so if you can help, it'll help a lot of people and not just me.
Thanks!
You need to use .value instead of .val() since you're using pure Javascript:
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if you want to use .val() method then you need a jQuery object:
var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();
You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:
$(document).ready(function () {
$("#submit").click(function () {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if (fname.length == 0) {
alert("Please input a first name");
} else if (lname.length == 0) {
alert("Please input a last name");
} else if (age.length == 0) {
alert("Please input an age");
}
});
});
Fiddle Demo
from your example, get elements by class name
var lists = document.getElementsByClassName("sex");
to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"
if you use native/pure javascript use .value not val() . val() is only for jquery
It looks like you're asking a couple questions at once.
As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.
I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.
As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.
Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/
One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.
Here is very simple way to make form validation using jquery
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: {
required: "Please provide a valid user name",
email: "Please enter a valid email address"
}
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
#import url("https://fonts.googleapis.com/css?family=Open+Sans");
/* Styles */
* {
margin: 0;
padding: 0;
}
body {
font-family: "Open Sans";
font-size: 14px;
}
.container {
width: 500px;
margin: 25px auto;
}
form {
padding: 20px;
background: #2c3e50;
color: #fff;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
form label,
form input,
form button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
form input {
height: 25px;
line-height: 25px;
background: #fff;
color: #000;
padding: 0 6px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
form button {
height: 30px;
line-height: 30px;
background: #e67e22;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
label.error {
color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
<h2>Registration</h2>
<form action="" name="registration">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john#doe.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="●●●●●" />
<button type="submit">Register</button>
</form>
</div>
function validate() {
var scheduledOn = $("#ScheduledOn").val();
var status = $(".Status option:selected").text();
var result = true;
if (id == "") {
var scheduledOn = $("#ScheduledOn").val();
var category = $(".categoryList option:selected").text();
var activityTask = $(".activityTaskList option:selected").text();
var lead = $("#LeadID").val();
var agent = $("#AgentID").val();
if (category == "Select Category") {
$("#categoryValidation").show();
$("#categoryValidation").text("The Category field is required");
}
else {
$("#categoryValidation").hide();
}
if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
var activityTask = $(".activityTaskList option:selected").text();
if (activityTask == "Select Activity Task") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
}
else {
$("#activityTaskValidation").hide();
}
}
if (category == "Joint Field Work") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Joint Field Work") {
if (lead == "" || lead == null || lead == "Select Lead") {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (category == "Agent Recruitment" || category == "Agent Development") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Direct Sales") {
if (lead == "" || lead == "Select Lead" || lead == null) {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (scheduledOn == "" || scheduledOn == null) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
}
return result;
}
else {
var scheduledOn = $("#NewScheduledOn").val();
var status = $(".Status option:selected").text();
if (document.getElementById("SetAppointment_Y").checked) {
var activityTask = $(".activityTaskList").val();
if (activityTask == null || activityTask == "") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
result = false;
}
else {
$("#activityTaskValidation").hide();
$("#scheduledOnValidation").hide();
}
if (status != null && (scheduledOn == "" || scheduledOn == null)) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
$("#statusValidation").hide();
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
$("#statusValidation").show();
}
}
}
return result;
}
I've have tried alot of different ways with removing the child and nothing has worked so faar, well it has to some degree, either i have no messages or i keep getting message that just add to the span without deleting the other
Tried reading up on how to remove the child, and have tried every different ways i've found to remove it, my code might be wrong on creating the child and append it etc. since it's the first time i use this way. Been trying with a while loop to remove, and the one that is already outcommented in the code, and with firstChild. and with different names instead of msg.
My code looks like this in my script:
function validateName(input, id)
{
var res = true;
var msg = document.getElementById(id);
var error = document.createElement("span");
var errorMsg = "";
if (input == "" || input < 2) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Input is to short!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && input.match(/\d/)) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Name contains a number!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && !input.match(/\d/)) {
res = true;
// removeChildren(msg);
}
return res;
}
My small test page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(e,id) {
if(validateName(document.form1.namefield.value, id) == false) {
document.getElementById("be").src="NotOkSmall.jpg";
}
if(validateName(document.form1.namefield.value) == true) {
document.getElementById("be").src="OkSmall.jpg";
}
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeydown="v1(be, div1)" >
<image id="be" src="NotOkSmall.jpg" alt="OkSmall.jpg" />
</div>
<input type="button" value="GO" onClick="v1(be)">
</form>
</body>
</html>
If anyone have any ideas to make it work I for one, would be a very happy guy :), as i have said before i am not even sure the creation of child is the correct way in this case. but as it works when i have removed removeChildren, it does write the correct messages, just dont delete any of them. So something must work..
Thanks.
You had some errors in your code like id.appendChild(error); where you had to use msg.appendChild(error);. Anyway I don't see a need to append/remove child nodes in this case. Just use hidden error placeholder and show it when you want to display an error message.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(imgId) {
var img = document.getElementById(imgId),
val = document.form1.namefield.value;
img.src = img.alt = validateName(val)
? "OkSmall.jpg"
: "NotOkSmall.jpg";
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeyup="v1('be');" >
<image id="be" src="NotOkSmall.jpg" alt="NotOkSmall.jpg" />
<span id="error-message" class="invis"></span>
</div>
<input type="button" value="GO" onClick="v1('be');">
</form>
</body>
</html>
CSS:
.invis {
display: none;
}
JavaScript:
function validateName(input) {
var res = true,
errorMsg,
errorContainer = document.getElementById('error-message');
if(input.length < 2) {
res = false;
errorMsg = "Input is to short!";
}
if(input.length >= 2 && /\d/.test(input)) {
res = false;
errorMsg = "Name contains a number!";
}
if(res) {
errorContainer.style.display = 'none';
} else {
errorContainer.innerHTML = errorMsg;
errorContainer.style.display = 'inline';
}
return res;
}
DEMO