Javascript validation highlight field - javascript

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;
}

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>

How trigger validation on a textbox when a button is pressed?

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.

javascript ignores validation by just toggling the value of an aria attribute despite empty value

I'm using the aria-required attribute in my HTML to check if the textbox is empty or not when blurred. If it has no value when blurred, it would be colored red, and back to white if it has a value. The result was surprising; it just toggles the boolean value of the attribute when focused and blurred and ignores the validation.
var txtbox = document.getElementById('textbox');
function isBlank(query) {
var required = (query.getAttribute('aria-required') === 'true');
if(!query.value) {
query.setAttribute('aria-required', !required);
return true;
} else {
query.setAttribute('aria-required', required);
return false;
}
}
function validateTextbox(e) {
var evt = e.target;
isBlank(evt);
}
txtbox.addEventListener('blur', validateTextbox);
[id="textbox"][aria-required="true"] {
background: #f00;
}
[id="textbox"][aria-required="false"] {
background: #fff;
}
<form action="" method="post">
<input type="text" name="name" id="textbox">
<input type="submit" value="Submit">
</form>
Try focusing then blurring the textbox without a value, it toggles the attribute value of the aria-required.
In your code, !required is inverting the boolean which is not what you want.
Here's a working example:
var textbox = document.getElementById('textbox')
function isBlank(target) {
var required = (target.getAttribute('aria-required') === 'true')
var isEmpty = !target.value.length
target.setAttribute('aria-required', isEmpty)
return isEmpty
}
function validateTextbox(event) {
var target = event.target
isBlank(target)
}
textbox.addEventListener('blur', validateTextbox)
JSFiddle demo: https://jsfiddle.net/ekj8brav/5/
Here's another way to validate input fields using the required attribute and styling it using CSS :valid and :invalid pseudo-selectors:
<form action="" method="post">
<input type="text" name="name" id="textbox">
<input type="submit" value="Submit">
</form>
CSS
#textbox:invalid {
background: #f00;
}
#textbox:valid {
background: #fff;
}
JS
var textbox = document.getElementById('textbox')
function isBlank(target) {
var isEmpty = !target.value.length
if (isEmpty) {
target.setAttribute('required', true)
target.setAttribute('aria-required', true)
}
return isEmpty
}
function validateTextbox(event) {
var target = event.target
isBlank(target)
}
textbox.addEventListener('blur', validateTextbox)
JSFiddle demo: https://jsfiddle.net/eph607up/2/

how to check the status of css through javascript

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;
}

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