Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/
Related
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>
trying to learn how to validate form input.
The inputs need to:
1 - Not be empty.
2 - Only contain alphabetic characters (no digits).
When I test (I've only focused on first name input field for now) it will give the correct error message if I leave it blank. But, if I but digits in the field it will submit instead of displaying error message.
What am I doing wrong?
HTML:
<form id="frm1">
<fieldset id="controls">
<div>
<label for="firstname">First Name: </label>
<input type="text" id="firstname">
<span id="errFname" class="errmsg">* You must enter a first name</span>
</div>
<div>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname">
</div>
<div>
<input type="submit" value="Submit">
</div>
</fieldset>
</form>
SCRIPT:
function checkForm(){
document.getElementById("frm1").onsubmit=function() {
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname)){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
}//close function
return false;
}//close function (checkForm)
window.onload=checkForm;
The problem is that you are returning inside each if block and that is making the whole submit callback to return.
You should create a variable and return only at the end. Something like this:
function checkForm(){
document.getElementById("frm1").addEventListener("submit", function(e) {
var errors = [];
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
errors.push("required");
}
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname) && errors.length === 0){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
errors.push("numeric");
}
//If you want, you can do something with your errors, if not, just return
//You should rethink about handling all errors here showing/hiding messages, etc.
if (errors.length > 0) {
e.preventDefault();
return false;
}
return true;
});//close function
}//close function (checkForm)
<script type="text/javascript">
function checkforinput() {
if (document.getElementById('fname').value == "") {
document.getElementById('fname').style.borderColor = "red";
document.getElementById('errMsg').innerHTML = "*Please enter First and Last Name";
} else {
document.getElementById('fname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg').innerHTML = "";
}
if (document.getElementById('lname').value == "") {
document.getElementById('lname').style.borderColor = "red";
document.getElementById('errMsg2').innerHTML = "*Please enter First and Last Name";
} else {
document.getElementById('lname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg2').innerHTML = "";
}
if (document.getElementById('email').value == "") {
document.getElementById('email').style.borderColor = "red";
document.getElementById('errMsg3').innerHTML = "*Please enter a valid email";
} else {
document.getElementById('email').style.borderColor = "#c5c5c5";
document.getElementById('errMsg3').innerHTML = "";
}
return false;
}
</script>
Hey guys. So my question is regarding this chunk of Javascript code. So these inputs (fname, lname, and email) have a span right next to them with the id errMsg that will display whatever the value of .innerHTML is. The validation works. Except whenever I fill in all the fields completely, my submit button won't process the form action i have in place. Nothing happens. Any ideas as to why this is happening. I feel it has to do something with the ELSE in the conditional statement but i don't know what it is exactly. The reason I use ELSE here, is because it turns the field back to how it looked like before. But maybe its actually screwing me over here. I need help guys. Any advice is appreciated.
This is my HTML code:
<form name="postform" action="postingprocessed.php" method="post" onsubmit="return checkforinput()">
<div class="fullName">
<input id="fname" type="text" maxlength="100" placeholder="First Name" name="first_name" /><span id="errMsg"></span>
<input id="lname" type="text" maxlength="100" placeholder="Last Name" name="last_name" /><span id="errMsg2"></span>
</div>
<input id="email" class="text" type="email" maxlength="100" placeholder="Email" name="email" /><span id="errMsg3"></span>
<br>
<input id="submitBtn" class="submitBtn" type="submit" value="Post This!" name="SubmitBtn" />
</form>
my submit button won't process the form action i have in place. Nothing happens.
Because you always return false, which tells browser not to process form. Return false only if some field is invalid and true otherwise:
var valid = true;
if (document.getElementById('fname').value == "") {
document.getElementById('fname').style.borderColor = "red";
document.getElementById('errMsg').innerHTML = "*Please enter First and Last Name";
valid = false;
} else {
document.getElementById('fname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg').innerHTML = "";
}
// ...
return valid;
Another recommendation. Don't use styles like your are now, this makes your code pretty obtrussive, verbose and hard to maintain (imagine, you want to change error border color - you need to change it on every field). Use CSS classes instead.
This will only submit the form if all the input is valid :) What we're doing is set flag=1 if any input is empty/invalid and in the end if flag is 1, form won't be submitted otherwise it will be submitted.
<script type="text/javascript">
function checkforinput() {
var flag=0;
if (document.getElementById('fname').value == ""){
document.getElementById('fname').style.borderColor = "red";
document.getElementById('errMsg').innerHTML = "*Please enter First and Last Name";
flag=1;
}
else {
document.getElementById('fname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg').innerHTML = "";
}
if (document.getElementById('lname').value == ""){
document.getElementById('lname').style.borderColor = "red";
document.getElementById('errMsg2').innerHTML = "*Please enter First and Last Name";
flag=1;
}
else {
document.getElementById('lname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg2').innerHTML = "";
}
if (document.getElementById('email').value == ""){
document.getElementById('email').style.borderColor = "red";
document.getElementById('errMsg3').innerHTML = "*Please enter a valid email";
flag=1;
}
else {
document.getElementById('email').style.borderColor = "#c5c5c5";
document.getElementById('errMsg3').innerHTML = "";
}
if(flag)
return false;
else
return true;
}
</script>
I'm trying to setup a 'Click to Chat' system for my company. It requires a form which captures some information from the user. When you submit the form, it's supposed to open a new window using the script in the .js file.
I tried to add some validation, which resulted in both an onclick, and an onsubmit function. When the form is subitted without the validation in place, it opens a new window using the BG.startChatWithIssueForm(this.form, true); function. But, For some reason, when I include the onsubmit for validation, the onclick ignores it completely.
I've tried nesting the BG.startChatWithIssueForm(this.form, true); function in different spots in the formValidator() function, but it still results in a file download prompt instead of opening a new window.
Not sure what I'm doing wrong. I've been researching this for weeks, and can't seem to come up with anything. Javascript is definitely not my forte, so any assistance would be greatly appreciated.
See the code below:
JS:
function Bomgar() {
var _host = "";
var _protoRe = /^(http|https):\/\//;
/* private */
function _createURL(params, forPopup) {
var qStr = "";
for (var k in params) {
qStr += "&"+encodeURIComponent(k)+"="+encodeURIComponent(params[k]);
}
qStr = "popup="+(forPopup ? "1" : "0") + "&c2cjs=1" + qStr;
return _host+"api/start_session.ns?"+qStr;
};
function _openWindow(params) {
return window.open(_createURL(params, true), 'clickToChat', 'toolbar=no,directories=no,status=no,menubar=no,resizable=yes,location=no,scrollbars=no');
};
function _redirectWindow(params) {
window.location.href = _createURL(params, false);
};
function _startChat(params, doFull) {
var w = _openWindow(params);
if (w && !w.closed) { return; }
else if (doFull) { _redirectWindow(params); return; }
};
function _startChatWithSurveyValues(surveyValues, fallbackToFullWindow) {
surveyValues.issue_menu = '1';
_startChat(surveyValues, fallbackToFullWindow);
};
/* public */
// Set the public site hostname that click to chat should be started on.
this.setSite = function(siteHostname) {
if (!_protoRe.test(siteHostname)) { siteHostname = "http://"+siteHostname; }
if (siteHostname[siteHostname.length-1] != '/') { siteHostname += '/'; }
_host = siteHostname;
};
// Start a click to chat session using a session key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKey = function(sessionKey, fallbackToFullWindow) {
var p = {short_key: sessionKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using a session key and external key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKeyAndExternalKey = function(sessionKey, externalKey, fallbackToFullWindow) {
var p = {short_key: sessionKey, external_key: externalKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using just an issue id and no other front end survey fields.
this.startChatWithIssueId = function(issueId, fallbackToFullWindow) {
_startChatWithSurveyValues({id: issueId}, fallbackToFullWindow);
};
// Start a click to chat session by passing the entire front end survey form element.
// This will submit all non-button input element values on the form.
// Any unexpected survey field names will be ignored.
this.startChatWithIssueForm = function(formElement, fallbackToFullWindow) {
var params = {};
for (var i = 0; i < formElement.elements.length; i++) {
var e = formElement.elements[i];
if (e.name && e.value && e.type && e.type != 'button' && e.type != 'submit') {
params[e.name] = e.value;
}
}
formElement = undefined;
params.issue_menu = '1';
_startChat(params, fallbackToFullWindow);
return false;
};
// Start a session with a representative id and name.
this.startChatWithRepIdName = function(repId, repName, fallbackToFullWindow) {
var p = {id: repId, name: repName};
_startChat(p, fallbackToFullWindow);
};
return this;
}
var BG = Bomgar();
HTML Code:
<script type="text/javascript" src="https://***.******.com/api/clicktochat.js"></script>
<script type="text/javascript">
BG.setSite("https://***.******.com");
</script>
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
// Check each input in the order that it appears in the form
if(madeSelection(issueid, "Please choose an issue"))
{
if(notEmpty(username, "Please enter your name"))
{
if(isAlphanumeric(username, "Numbers and Letters Only for name"))
{
if(notEmpty(userid, "Please enter your user ID"))
{
if(isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
{
if(notEmpty(issuedesc, "Please type a description of your problem"))
{
}
}
}
}
}
}
}
//check to make sure user selected their issue
function madeSelection(elem, helperMsg){
if(elem.selectedIndex == 0 ){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}else{
return true;
}
}
//check to make sure user entered something in the particular field
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
//check to make sure user only entered numeric characters
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user only entered alpha characters
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user entered only alpha or numeric characters
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<script type="text/javascript">
/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul#REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
function handleEnter (field, event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
}
else
return true;
}
</script>
<form action="https://***.******.com/api/start_session.ns" onsubmit="return formValidator();" method="get">
What issue are you having?
<select onkeypress="return handleEnter(this, event)" id="issueid" name="id">
<option value="">Choose</option>
<option value="1">I need help getting started</option>
<option value="2">I am receiving an error</option>
</select>
<br />
Your First and Last Name: <input onkeypress="return handleEnter(this, event)" type="text" id="username" name="customer_name" /><br />
Your User ID (ABC1234): <input onkeypress="return handleEnter(this, event)" type="text" id="userid" name="customer_id" /><br />
Describe Your Issue: <textarea onkeypress="return handleEnter(this, event)" id="issuedesc" name="customer_desc"></textarea><br />
<input onkeypress="return handleEnter(this, event)" type="hidden" name="issue_menu" value="1" />
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
<br>
<input onkeypress="return handleEnter(this, event)" type="button" name="reset_form" value="Clear" onclick="this.form.reset();">
</form>
</body>
Have you tried replacing the submit button with a regular button, doing the validation in the onClick handler, and then submitting the form from within the onClick handler?
Edit: e.g. replace
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
with
<input onkeypress="return handleEnter(this, event)" type="button" value="Submit" onclick="BG.handleSubmit(this.form, true);" />
Then maybe use a Javascript function like this (I'm not sure exactly what order you want these things to happen in):
BG.handleSubmit = function(formElement, fallBackToFullWindow) {
if (!formValidator())
return;
BG.startChatWithIssueForm(formElement, fallBackToFullWindow);
formElement.submit();
return false;
}
Edit: Your validation function should probably return false if it finds something invalid.
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
var valid = true;
// Check each input in the order that it appears in the form
if(!madeSelection(issueid, "Please choose an issue"))
valid = false;
if(!notEmpty(username, "Please enter your name"))
valid = false;
if(!isAlphanumeric(username, "Numbers and Letters Only for name"))
valid = false;
if(!notEmpty(userid, "Please enter your user ID"))
valid = false;
if(!isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
valid = false;
if(!notEmpty(issuedesc, "Please type a description of your problem"))
valid = false;
return valid;
}
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" />