JS wont recognize a variable within angular controller object - javascript

Im trying to create a simple login verification, however the validation function seizes to function when the validation comparison begins, and the console sais that the variable "userName is not defined" although it clearly is.
Can enyone tell me what am i defining wrong?
the angular controller code:
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
this.userName = "";
this.password = "";
this.userNameValid = true;
this.passwordValid = true;
/*submit the form*/
this.submit = function () {
alert("submit");
this.validate();
};
/* make sure user name and password has been inserted*/
this.validate = function () {
alert("validate");
var result = true;
this.userNameValid = true;
this.passwordValid = true;
if (this.userName == "") {
alert("username="+userName);
this.userNameValid = false;
result = false;
}
if (this.password == "") {
this.passwordValid = false;
result = false;
}
alert("validuserNameValid==" + userNameValid + " passwordValid==" + passwordValid);
return result;
};
});
the HTML form:
<body ng-app="LoginApp" ng-controller="LoginController as LoginController">
<form role="form" novalidate name="loginForm" ng-submit="LoginController.submit()">
<div id="loginDetails">
<div class="form-group">
<label for="user"> User Name:</label>
<input type="text" id="user" class="form-control" ng-model="LoginController.userName" required />
<span ng-show="LoginController.userNameValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" id="password" class="form-control" ng-model="LoginController.password" required />
<span ng-show="LoginController.passwordValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
{{"entered information:" +"\n"+LoginController.userName+" "+ LoginController.password}}
</div>
</div>
</form>
</body>
the log:
Error: userName is not defined
this.validate#http://localhost:39191/login.js:23:13
this.submit#http://localhost:39191/login.js:11:9
anonymous/fn#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js line 231 > Function:2:292
b#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:126:19
Kc[b]</<.compile/</</e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:195
uf/this.$get</m.prototype.$eval#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:103
uf/this.$get</m.prototype.$apply#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:335
Kc[b]</<.compile/</<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:245
Rf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:37:31
Qf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:36:486

Always use this judiciously. I would recommend you to store the reference of this in variable then use it wherever required.
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
//Store the reference of this in a variable
var lc = this;
//Use the stored refrence
lc.userName = "";
/* make sure user name and password has been inserted*/
lc.validate = function () {
if (lc.userName == "") {
alert("username="+userName);
lc.userNameValid = false;
result = false;
}
};
});

inside your alert boxes you have not mentioned this.userName try removing the alert boxes or change them.

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>

Form validation error message is overriding in javascript (only )

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/

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

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

onsubmit passes even when js function returns false

I've read many posts considering this problem and for some reason none of the solutions work for me. I have several js functions for validation that are called in the main one that is appointed to the onSubmit tag in the form. Here is the js code:
<script type="text/javascript">
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
return true;
}
return false;
}
</script>
<script type="text/javascript">
function validacijaSifri(fieldId1, fieldId2)
{
var two = document.getElementById(fieldId1).value;
var three = document.getElementById(fieldId2).value;
if(two == three) { return true; }
alert("Warning!! passcodes must match!!!");
return false;
}
</script>
<script type="text/javascript">
function validacijaUsername(usname)
{
var letters = /^[A-Za-z]+$/;
if(letters.test(usname.value))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
document.getElementById('usrname').focus();
return false;
}
}
</script>
<script type="text/javascript">
function validacijaEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(email))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
document.getElementById(email).focus();
return false;
}
}
and here is the html form code
<form class="form-signin" onSubmit="return validacijaForme();" name="registerForm" method = "POST" action="test.php" enctype="multipart/form-data">
<h2 class="form-signin-heading">Registracija</h2>
<input type="text" class="form-control" placeholder="Username" name="usrname" id="usname" autofocus>
<input type="text" class="form-control" placeholder="E-mail" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass1">
<input type="password" class="form-control" placeholder="Confirm password" id="pass2">
<button class="btn btn-lg btn-primary btn-block" name="dugme" type="submit">Register</button>
The problem is that all the alerts are working, meaning that those functions do validate the fields, and should return false, but the onSubmit tag doesn't seem to accept that value from the function.
The form doesn't submit and doesn't pass to test.php only if I type this:
<form class="form-signin" onSubmit="return false" name="registerForm" method = "POST" action="test.php" enctype="multipart/form-data">
submit the form with javascript submit()
<form id="myform" class="form-signin" onSubmit="validacijaForme();" name="registerForm"
method = "POST" action="test.php" enctype="multipart/form-data">
And in your function:
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
document.getElementById("myform").submit();
return false;
}
return false;
}
Your problem is related to your username id/name consistency. Use the console (F12) to debug this kind of thing.
<input type="text" class="form-control" placeholder="Username" name="usRname" id="usname" autofocus>
Change:
document.getElementById('usrname').focus();
To:
document.getElementById('usname').focus();
There are lots of errors in your code buddy | WORKING DEMO
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
return true;
}
return false;
}
function validacijaSifri(fieldId1, fieldId2)
{
var two = fieldId1.value;
var three = fieldId2.value;
if(two == three) { return true; }
alert("Warning!! passcodes must match!!!");
return false;
}
function validacijaUsername(usname)
{
var letters = /^[A-Za-z]+$/;
if(letters.test(usname.value))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
document.getElementById('usname').focus();
return false;
}
}
function validacijaEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(email.value))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
document.getElementById('email').focus();
return false;
}
}

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