I have a JavaScript file that validates if the text-box is filled out or not.
I want to make it that if all the text-boxes are all filled out correctly, it should go on to the next page or what ever the case is. (In my case just to display an alert message box.) I would appreciate any answer as soon as possible. Thanks in advance.
HTML
<form name="form" onSubmit="return validate()" method="post">
<p>
<label class="tittle">Name:</label>
<span>
<input type="text" name="firstname"
placeholder="First Name" class="info"
size="25" maxlength="25"
onBlur="return validateFirstName()">
<label class="fillerror" id="fillFirst">
First name is required
</label>
</span>
<span>
<input type="text" name="lastname"
placeholder="Last Name" class="info"
size="25" maxlength="25"
onBlur="return validateLastName()">
<label class="fillerror" id="fillLast">
Last name is required
</label>
</span>
</p>
<p>
<input type="button" name="register"
value="Register" class="register"
onClick="return validateFirstName(),
validateLastName(), allValidated();">
</p>
</form>
JavaScript
function xValidate(inbox, fill)
{
inbox.style.backgroundColor="rgba(255, 0, 0, .1)";
inbox.style.borderLeft="3px solid red";
fill.style.display="block";
}
function yValidate(inbox, fill)
{
inbox.style.backgroundColor="white";
inbox.style.borderLeft="3px solid rgb(169, 184, 1)";
fill.style.display="none";
}
function validateFirstName()
{
var frstnm = document.forms["form"] ["firstname"].value;
var inbox = document.forms["form"] ["firstname"];
var firstname = document.getElementById("fillFirst");
if (frstnm==null || frstnm=="" || frstnm==" ")
{
xValidate(inbox, firstname);
}
else
{
yValidate(inbox, firstname);
}
}
function validateLastName()
{
var lstnm = document.forms["form"] ["lastname"].value;
var inbox = document.forms ["form"] ["lastname"];
var lastname = document.getElementById("fillLast");
if (lstnm==null || lstnm=="" || lstnm==" ")
{
xValidate(inbox, lastname);
}
else
{
yValidate(inbox, lastname);
}
}
This is the function I need help on, all other code here was just for information to understand this last statement:
function allValidated()
{
var allrGood = document.getElementsByClassName("fillerror");
if (allrGood.style.display="none" == true)
{
alert("They're all good");
}
else if (allrGood.style.display="block" == true)
{
alert("Something is displayed 'block'");
}
}
If it doesn't work with an 'if' statement, then maybe it would work with a 'for' or 'while' statement (looping statement) then please show me.
First I would really suggest that you start using jQuery. It'll make things quite easy.
Here is a pure JS solution though -
First assign a particular class to all the controls that need to be
validated.
On the onchange event of the controls, if the controls are valid,
add a certain class say - ctrlValid , else add another class -
ctrlInvalid.
Then on the click of the button, get all elements by the class name
ctrlInvalid
Check if the length is 0, if it is - redirect, else show message.
If you continue to use your solution then -
var blIsFormValid = true;
for(var i =0; i < allrGood.length; ++i)
{
if(allrGood[i].style.display != 'none')
{
blIsFormValid = false;
break;
}
}
if(blIsFormValid)
{
// Redirect check - http://stackoverflow.com/a/4745622/903324
window.location = "http://www.yoururl.com";
}
else
{
// Show message...
}
One problem with your code is document.getElementsByClassName() returns an array of elemets, not just one element. So allrGood.style doesn't quite make sense.
Also, allrGood.style.display="none" assigns "none" to allrGood.style.display instead of comparing them. Remember to use == for a loose comparison or === for a strict comparison.
Using jQuery you can iterate through each label of class fillerror and check to see if it's visible, like so:
function areTheyAllValidated() {
var valid = true;
$('label.fillerror').each(function(index, element) {
if ($(element).is(":visible"))
valid = false;
});
return valid;
}
You have to pop a class or ID on your alert control so you can style that sucka.
Something like below should get you in a decent direction. With another bell and whistle for sags.
'SuperCool': function() {
var sName = document.getElementById('ip1').value;
Alert.SuperCool( "Thank you "+sName+". Could be expanded to do something a little more clever" );
}
Example alert styling.
.SuperCool {
background: red;
width: 200px;
height: 100px;
}
Related
I've written a program that should display an image of a beverage or an alert window depending on the user's age input. The problem is that regardless of what value is submitted it only executes the 'if' portion of the statement. None of the other conditions are being checked prior to execution. I have tried using getElementById with the element id in place of querySelector but the program did not run at at all. I have tried querySelector with the button tag as well as trying the input tag. That also did not work.
function strt() {
let theButton = document.getElementById('aButton');
theButton.addEventListener('click', verifyAge);
}
function verifyAge() {
let patronAge = document.querySelector('age');
let primaryImg = document.getElementById('mainImg');
if (patronAge < 21) {
primaryImg.src = 'images/cola.jpg';
} else if (patronAge >= 21) {
primaryImg.src = 'images/tallboy.jpg';
} else if (patronAge <= 0) {
alert('Please enter a valid number:');
} else if (patronAge == NaN) {
alert('That is not a valid number. Please try again.');
}
}
window.addEventListener('load', strt);
<img src="images/bar&grill.png" alt="barandgrill" id="mainImg">
<br>
<form>
<label for="age">Please enter your age:</label>
<input type="text" id="age" required>
<button id="aButton" type="button">Get Drinks</button>
</form>
Instead of writing this:
let patronAge = document.querySelector('age');
you should write the following:
let patronAge = parseInt(document.querySelector('#age').value);
There are a few problems with your approach.
querySelector('age') looks for an element with tag age, this does not exist. Since you're using querySelector you need to specify a # symbol to search for an id.
You need to access the value of the HTMLElement
You need to parse the value as a number
couple of minor problems. They are pretty easy to spot. Look over the snippet and let me know if you don't understand anything.
function strt() {
let theButton = document.getElementById('aButton');
theButton.addEventListener('click', verifyAge);
}
function verifyAge() {
let patronAge = document.getElementById('age').value;
let primaryImg = document.getElementById('mainImg');
if (patronAge < 21) {
primaryImg.src = 'https://via.placeholder.com/120';
} else if (patronAge >= 21) {
primaryImg.src = 'https://via.placeholder.com/150';
} else if (patronAge <= 0) {
alert('Please enter a valid number:');
} else if (typeof(patronAge) == 'string') {
alert('That is not a valid number. Please try again.');
}
}
window.addEventListener('load', strt);
<img src='https://via.placeholder.com/100' alt="barandgrill" id="mainImg">
<br>
<form>
<label for="age">Please enter your age:</label>
<input type="text" id="age" required>
<button id="aButton" type="button">Get Drinks</button>
</form>
I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.
I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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 (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>
I'm creating a simple JS validation for my form. I need it to highlight red onblur when not filled out, and green once you fill it in afterwards. Sorry, not allowed to imbed images in my posts yet :L
Any help appreciated, thank you.
This is the Html:
<form id="surveyForm">
Favourite movie?
<input type="text" id="favMov" onblur="return $formValidation()"/>
<span id="errorStyle"></span>
</form>
This is the Js:
function $formValidation(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Just for testing - alert(val.length);
//if the length value of the text field is blank - show error
if (val == "") {
document.getElementById("errorStyle").style.borderColor = "red";
return false
} else {
//if they are not blank remove error text
document.getElementById("errorStyle").style.borderColor = "green";
}
}
You can find a fiddle sample here:
http://jsfiddle.net/a45gn9w4/
You need to listen to the submit of your form and call the function formValidation()
Then you can actually get those elements and validate if it is correct or not.
This is the html:
<form id="surveyForm" method="post" action="some_url_to_post">
<label id="">Favourite movie?<span id="error" class="noErrorHappen">*</span></label>
<input type="text" id="favMov" name="favMov">
<br/>
<input type="submit" id="validator" value="Submit">
</form>
This is the js:
var error = document.getElementById("error");
var form = document.forms.surveyForm,
elem = form.elements;
function formValidation() {
if(!elem.favMov.value){
alert('please input text.');
elem.favMov.focus();
error.className = "errorHappen";
return false;
} else {
error.className = "noErrorHappen";
return true;
}
}
form.onsubmit = formValidation;
This is the CSS:
.errorHappen {
display: block;
color: red;
}
.noErrorHappen {
display: none;
}
#error {
float: left;
}
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" />