could not remove the error message on validation - javascript

I was testing a learning Form validation, I could not remove error text.
The HTML Code was like this
<div class="form-group">
<label for="">Requester<span class="required text-danger">*</span></label>
<input type="text" class="form-control">
<small style="display: none"></small>
</div>
With Jquery to validate
var errors = 0;
var submitted = false;
var addError = function (element, siblings, errorMessage) {
if (element.style.display == "none") {
console.log(element);
return;
}
errors++;
$(element).addClass("text-error")
siblings.each(function (index, sib) {
if (sib.tagName == "SMALL") {
sib.innerText = errorMessage
$(sib).addClass("text-danger");
$(sib).addClass("font-weight-bold");
$(sib).show();
}
})
};
And a function to remove the errors
var removeError = function (element, siblings) {
$(element).removeClass("text-error");
siblings.each(function (index, sib) {
if (sib.tagName == "SMALL") {
sib.innerText = ""
$(sib).removeClass("text-danger");
$(sib).removeClass("font-weight-bold");
$(sib).hide();
}
})
};
When I removed the <small style="display: none"></small> and <span class="required text-danger">*</span> it did not make any change it still shows RED error box and Sweetalert.js message,
is there anyway I can make it work, how can I remove the error for non required fields.
Ref code pen link :https://codepen.io/dunya/pen/KYdQPd
Many thanks

Related

ValidateForm How to validate and show text when submit button was clicked in JavaScript

I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>

I am trying to store data in sql server but i run into an error which i dont know how to fix

I am trying to store the users name, email and their message on my contact page. When i run my website and go on the contact page and type all the details inside the contact form and click the send button (send button called submitBtn) i get the error you can see below in the image.
error message:
c# code: this c# code is for the send button.
protected void submitBtn_Click(object sender, EventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(ConfigurationManager.ConnectionStrings["Fasthosts_MMConnectionString"].ConnectionString);
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into Contact(UserName, Email, Message) " +
"values(#UserName, #Email, #Message)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#UserName", tbUserName.Text);
com.Parameters.AddWithValue("#Message", userMessage.Text);
com.Parameters.AddWithValue("#Email", userEmail.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
//throw Exception ;
Response.Write("Error Message: " + problem.ToString());
throw;
}
}
html code:
<div id="contactForm" class="contactForm">
<div id="formHeader" class="formHeader">
<h1 id="message">Contact Us :)</h1>
</div>
<div id="formBody" class="formBody">
<form action="homepage.aspx" method="POST" name="contactForm">
<div class="inputContainer">
<label for="userName">
<i class="fa fa-lg fa-fw fa-user"></i>
</label>
<asp:TextBox ID="tbUserName" placeholder="John Smith" runat="server"></asp:TextBox>
<!--<input name="name" id="userName" type="text" placeholder="John Smith">-->
</div>
<div class="inputContainer">
<label for="userEmail">
<i class="fa fa-lg fa-fw fa-envelope"></i>
</label>
<asp:TextBox ID="userEmail" placeholder="jsmith#domain.com" runat="server"></asp:TextBox>
</div>
<div class="inputContainer">
<asp:TextBox ID="userMessage" rows="10" placeholder="Enter your message" runat="server" Height="100px"></asp:TextBox>
</div>
<!--<input id="submitBtn1" class="submitBtn" type="submit" value="Send">-->
<asp:Button ID="submitBtn" Class="submitBtn" runat="server" Text="Send" OnClick="submitBtn_Click" />
</form>
</div>
javascript code :
(function () {
"use strict";
var //GLOBAL VARIABLES
input,
container,
//CSS CLASSES
classSuccess = "success",
classError = "error",
//FORM VALIDATOR
formValidator = {
init: function () {
this.cacheDom();
this.bindEvents();
},
cacheDom: function () {
//MAIN PARENT ELEMENT
this.contactForm = document.getElementById("contactForm");
//MAIN FORM ELEMENTS
this.formHeader = document.querySelector("#formHeader h1");
this.formBody = document.getElementById("formBody");
this.inputContainer = document.getElementsByClassName("inputContainer");
//USER INPUT ELEMENTS
//INPUT FIELDS
this.fields = {
userName: document.getElementById("userName"),
userEmail: document.getElementById("userEmail"),
userMessage: document.getElementById("userMessage")
};
this.submitBtn = document.getElementById("submitBtn");
},
bindEvents: function () {
var i;
//RUN RULES ON SUBMIT BUTTON CLICK
this.submitBtn.onclick = this.runRules.bind(this);
//BIND EVENTS TO EACH INPUT FIELD
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//VARIABLES
input = this.fields[i];
container = input.parentElement;
//RUN RULES WHEN INPUT HAS FOCUS
input.onfocus = this.runRules.bind(this);
//RESET ERRORS WHEN CONTAINER IS CLICKED
container.onclick = this.resetErrors.bind(this, input);
}
}
},
runRules: function (evnt) {
var target = evnt.target,
type = evnt.type;
//IF EVENT ON SUBMIT BUTTON
if (target === this.submitBtn) {
//PREVENT FORM SUBMITTION
this.preventDefault(evnt);
//IF INPUT HAS FOCUS
} else if (type === "focus") {
//RESET CLASSLIST
this.resetClassList(target.parentElement);
//RESET ERRORS
this.resetErrors(target);
return false;
}
//RESET CLASSLIST
this.resetClassList();
//CHECK FIELDS
this.checkFields();
},
preventDefault: function (evnt) {
//PREVENT DEFUALT
evnt.preventDefault();
},
checkFields: function () {
var i,
validCount = 0,
//EMAIL FILTER
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//CYLCE THROUGH INPUTS
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
input = this.fields[i];
//CHECK IF FIELD IS EMPTY
if (input.value === "") {
//ADD ERROR CLASS
this.addClass(input, classError);
//CHECK IF EMAIL IS VALID
} else if (i === "userEmail" && !filter.test(input.value)) {
//ADD ERROR CLASS
this.addClass(input, classError);
} else {
//FIELD IS VALID
this.addClass(input, classSuccess);
validCount += 1;
}
}
}
//IF ALL FEILDS ARE VALID
if (validCount === 3) {
//SUBMIT FORM
this.submitForm();
}
},
addClass: function (input, clss) {
container = input.parentElement;
//IF INPUT HAS ERROR
if (clss === classError) {
//SHOW ERROR MESSAGE
this.errorMessage(input);
}
//ADD CLASS
input.parentElement.classList.add(clss);
},
errorMessage: function (input) {
var message;
//IF USERNAME HAS ERROR
if (input === this.fields.userName) {
message = "Please enter your name";
//ELSE IF USEREMAIL HAS ERROR
} else if (input === this.fields.userEmail) {
message = "Please enter a valid email";
//ELSE IF USERMESSAGE HAS ERROR
} else if (input === this.fields.userMessage) {
message = "Please enter your feedback";
}
this.renderError(input, message);
},
renderError: function (input, message) {
var html;
//GET INPUT CONTAINER
container = input.parentElement;
//RENDER HTML
html = document.createElement("div");
html.setAttribute("class", "message");
html.innerHTML = message;
//IF MESSAGE ELEMENT DOESN'T EXIST
if (!container.getElementsByClassName("message")[0]) {
//INSERT MESSAGE TO INPUT CONTAINER
container.insertBefore(html, container.firstElementChild);
}
},
resetClassList: function (input) {
var i;
//IF TARGETING SPECIFIC INPUT
if (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//REMOVE CLASSES
container.classList.remove(classError, classSuccess);
//FOCUS ON INPUT FIELD
input.focus();
} else {
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//REMOVE CLASSES FROM ALL FIELDS
this.fields[i].parentElement.classList.remove(classError, classSuccess);
}
}
}
},
resetErrors: function (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//IF CONTAINER CONTAINS ERROR
if (container.classList.contains(classError)) {
//RESET CLASSES
this.resetClassList(input);
}
},
submitForm: function () {
var waitForAnimation;
//ADD SUCCESS CLASS
this.contactForm.classList.add(classSuccess);
//WAIT FOR ANIMATION TO FINISH
this.changeHeader("Sent Succesfully");
//WAIT FOR ANIMATION TO FINISH
setTimeout(
this.changeHeader.bind(this, "Thank you for your feedback"),
1200
);
},
changeHeader: function (text) {
//CHANGE HEADER TEXT
this.formHeader.innerHTML = text;
}
};
//INITIATE FORM VALIDATOR
formValidator.init();
})();
Write this in first line of page directive in source code
<%# Page EnableEventValidation="false" %>

error classes do not show up when form is submitted

I'm trying to validate my signup form using JavaScript. I submit the form and the default action is prevented but none of my error handler classes show up, nor do I get any errors in my error log. if anyone can show me what I'm doing wrong, it would greatly appreciated. I'm trying to show a red background on the input fields if the user doesn't fill in the input.
$(document).ready(function () {
$("#signupForm").submit(function (e) {
removeFeedback();
var errors = validateSignup();
if (errors == "") {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
});
function validateSignup() {
var errorFields = new Array();
//Check required fields to see if they have anything in them
if ($('#signupFirst').val() == "") {
errorFields.push('first');
}
if ($('#signupLast').val() == "") {
errorFields.push('last');
}
if ($('#signupEmail').val() == "") {
errorFields.push('email');
}
if ($('#signupPassword').val() == "") {
errorFields.push('pwd');
}
if (!($('#signupEmail').val().indexOf(".") > 2) && ($('#signupEmail').val().indexOf("#"))) {
errorFields.push('email');
}
return errorFields();
}
function provideFeedback(errorFields) {
for (var i = 0; i < errorFields.length; i++) {
$("#" + errorFields[i]).addClass("inputError");
$("#" + errorFields[i] + "Error").removeClass("errorFeedback");
}
}
function removeFeedBack() {
$('input').each(function () {
$(this).removeClass("inputError");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="index-bg-wrapper">
<div class="main-signup-container">
<form id="signupForm" class="signup-form" action='include/signup.inc.php' method='POST'>
<input id="signupFirst" type="text" name="first" placeholder="First Name">
<input id="signupLast" type="text" name="last" placeholder="Last Name">
<input id="signupEmail" type="text" name="email" placeholder="Email">
<input id="signupPassword" type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Signup</button>
</form>
</div>
</div>
</body>
This is not ok:
return errorFields(); // Here you're trying to call a function with an array.
Just return the array: return errorFields;
Another problem is the comparison:
if (errors == "") { // This is not ok (it's always false), so, what you want to check is the length of errors.
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
So, check for the length:
if (errors.length === 0) {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
Here you go buddy, I have fixed multiple errors though very minor in your code but its working fine now.
Plnkr:
http://embed.plnkr.co/MaUzZh1zUFBL4y8qAf6n/
You were pushing wrong name inside the errorFields array.
Due to wrong field name and DOM id mismatch jquery couldn't find the element and apply the class.
I hope you can compare and get this code working.

Is there any way to obtain content from a form to display in the client (view/template) with JavaScript after submit?

I have a form, a simple form:
<form>
<input class="u-full-width" type="text" placeholder="First Name" id="firstNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="text" placeholder="Last Name" id="lastNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="email" placeholder="Email" id="emailInput">
<span class="error" aria-live="polite"></span>
<select class="u-full-width" name="state" id="stateInput">
<option value="selectstate">State</option>
</select>
<span class="error" aria-live="polite"></span>
<input id="submit" class="button-primary submit_button" type="submit" value="Submit">
<span class="success" aria-live="polite"></span>
</form>
Essentially I have a eventHandler wired to the form which is listening for the submit event.
theForm.addEventListener('submit', function(e) {
var x = validate(e);
if (x) {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
}
}, false);
The validate function:
function validate(e) {
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
return true;
}
}
I would think the conditional in the handler would work like this:
It would only fire if the x was true; which it would be if there was a true outcome i.e. the form submitted successfully. the obj, would get filled with the dat and then I would console.log the fields via a for in loop
I am having problems understanding why you can't get data from this function?
Any help would be appreciated...
var formData = { is contained within your validate() function but you are trying to access it from within the anonymous form submit function.
To access it in both places, you either need to pass it as an argument or declare it in a higher scope, outside of both functions like this:
var formData = {
firstName: null,
lastName: null,
email: null,
stateInput: null
}
function validate(e){
}
theForm.addEventListener('submit', function(e) {
});
Additionally, right now, your "State" dropdown will always fail validation because you only have one choice and that choice is considered invalid by your validation function.
Your tests for input in the text fields that check for null is not going to help you at all because an input that contains no data will always return '', which you are already testing for, so just that one test is fine, although you may want to change it to test for: input.value.trim() === '' because the trim() function will remove any leading or trailing spaces in the input.
Finally, when all the form data is valid, you will only see the console report for a brief moment, because the form will submit and cause a redirect to the form's action, so the current page will unload and the console will clear itself out.
Here's the whole thing put together:
var formData = {
firstName: null,
lastName: null,
email: null,
stateInput: null
}
var theForm = document.querySelector("form");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
var emailInput = document.getElementById("emailInput");
var stateInput = document.getElementById("stateInput");
theForm.addEventListener('submit', function(e) {
if (validate(e)) {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
logger('There is now data from the form: :) ');
}
}, false);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (firstNameInput.value.trim() === '') {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (lastNameInput.value.trim() === '') {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value.trim())) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if (stateInput.value === 'selectstate') {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
logger('There is at least one empty field in the form: ');
return false;
} else {
return true;
}
}
function logger(message){
console.clear();
console.log(message);
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
// This line will fail here in Stack Overflow, but is correct and
// will work in a real browser environment. Uncomment it for your use.
// localStorage.setItem(prop, formData[prop]);
}
}
#spacer { height:100px; }
<form>
<input class="u-full-width" type="text" placeholder="First Name" id="firstNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="text" placeholder="Last Name" id="lastNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="email" placeholder="Email" id="emailInput">
<span class="error" aria-live="polite"></span>
<select class="u-full-width" name="state" id="stateInput">
<option value="selectstate">State</option>
<option value="someSate">Some State</option>
</select>
<span class="error" aria-live="polite"></span>
<input id="submit" class="button-primary submit_button" type="submit" value="Submit">
<span class="success" aria-live="polite"></span>
</form>
<div id='spacer'></div>

Validation stuck at first validation

I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />

Categories