Related
I am using knockout.js in a huge project with multiple dependencies and that is why I am unable to create a demo. However, I have a dynamic form that can add/remove multiple input field pairs of username and password as follows:
Input field1: [_________] : [_________] x
Input field2: [_________] : [_________] x
Input field3: [_________] : [_________] x
Input field4: [_________] : [_________] +
That creates an object on submit, something like:
{
credentials:{
Username1: password1,
Username2: password2,
Username3: password3,
Username4: password4,
}
}
Form Validation:
If at least one row of username and password is not empty, ignore
all other empty rows. But if all username and password entries are
empty, then throw an error message.
If either username or password is empty in an input field row, throw
an error.
if Duplicate usernames, throw an error.
Result:
I am able to validate almost everything except if the only first row of input fields is empty and others are not.
Problem:
If any input field except “Input field1” has empty username and password, it ignores that row. But, if the “Input field1” has an empty username and password fields and others are not empty, it doesn’t ignore the first row, rather it throws an error. It can be a series of multiple input fields being empty and just the last one being not empty.
Javascript:
// make sure we visit every entry to ensure
// that we highlight each validation error
userpassEntries.forEach(function(displayEntry) {
var username = displayEntry.username;
var password = displayEntry.password;
// reset the error message to get new ones (if any)
displayEntry.errUsername(null);
displayEntry.errPassword(null);
if (username === '' && password === '') {
// If at least one row of username and password
// is not empty ignore all other empty rows.
// But if all username and password entries are
// empty, then throw the following error message.
if (Object.keys(credentials).length === 0) {
displayEntry.errUsername('Please enter a username');
displayEntry.errPassword('Please enter a password');
// mark invalid
isValid = false;
}
// ignore the the entry
return;
} else if (username !== '' && password === '') {
displayEntry.errPassword('Please enter a password');
} else if (username === '' && password !== '') {
displayEntry.errUsername('Please enter a username');
} else if (
userpassEntries.filter(function(user) {
return user.username === username;
}).length > 1
) {
displayEntry.errUsername('Duplicate username');
} else {
// if the fields had values and vlaidation passed we can safely add them
credentials[username] = password;
}
if (isValid) {
isValid =
displayEntry.errUsername() === null &&
displayEntry.errPassword() === null;
}
});
if (!isValid) {
// do not proceed to save if there were any invalid fields
return;
}
payload = {
credentials: credentials
};
that.onSubmit(payload);
Question:
How can I ignore the rows of empty input fields and still capture the rest of the filled ones?
Example Scenario:
Input field1: [_________] : [_________] // This should be ignored but it is not working
Input field2: [Username2] : [password2]
Input field3: [Username3] : [password3]
Input field4: [_________] : [_________] // This is getting ignored at the payload
The following should still send the last entry ignoring the first two
That seems easy enough. I'm not really sure where it's going wrong in your code, but I wrote something very similar and it seems to work fine.
function validate () {
var validCredentials = {};
vm.credentials.forEach(function (credentialObj) {
credentialObj.errorMsg('');
if (validCredentials.hasOwnProperty(credentialObj.username())) {
credentialObj.errorMsg('Duplicate username!');
} else {
if (credentialObj.username() && credentialObj.password()) {
validCredentials[credentialObj.username()] = credentialObj.password();
} else {
credentialObj.errorMsg('Please enter a username and/or password');
}
}
});
// now validCredentials will contain the valid credentials as key/value pairs
vm.validCredentials(JSON.stringify(validCredentials));
}
Working fiddle: https://jsfiddle.net/thebluenile/4ox92gz7/
It's kind of hard to spot exactly what's going wrong in your code, so I thought I'd chip in with an approach of a slightly different style.
Here's how to do validation using mainly ko.pureComputed values and two models:
Form takes care of the validity of the total set of inputs (Rule 1)
Entry takes care of the validity of one specific input (Rules 2 & 3)
To support the duplicate username test, Entry needs a reference to its Form.
function Form() {
this.entries = [ new Entry(this), new Entry(this), new Entry(this), new Entry(this) ];
this.isEmpty = ko.pureComputed(() =>
this.entries.every(e => e.isEmpty())
);
this.isValid = ko.pureComputed(() =>
this.entries.every(e => e.isValid())
);
this.canSave = ko.pureComputed(() =>
!this.isEmpty() && this.isValid()
);
this.save = () => {
console.log(this.entries
.filter(e => e.isFilledIn())
.map(e => e.toJS()));
}
};
function Entry(form) {
this.username = ko.observable("");
this.password = ko.observable("");
this.isEmpty = ko.pureComputed(
() => !this.username() && !this.password()
);
this.isFilledIn = ko.pureComputed(
() => this.username() && this.password()
);
this.isDuplicate = ko.pureComputed(
() => {
if (!this.username()) return false;
const myIndex = form.entries.indexOf(this);
const beforeMe = form.entries.slice(0, myIndex);
return beforeMe.some(e => e.username() === this.username());
}
);
this.isValid = ko.pureComputed(
() => this.isEmpty() || (this.isFilledIn() && !this.isDuplicate())
);
this.toJS = () => ({ username: this.username(), password: this.password() });
};
ko.applyBindings(new Form());
.highlightEmpty > .empty {
border-bottom: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: entries">
<li data-bind="css: { highlightEmpty: !isEmpty() }">
<input data-bind="textInput: username, css: { empty: !username() }">:
<input data-bind="textInput: password, css: { empty: !password() }">
<p data-bind="visible: isDuplicate">
The username <strong data-bind="text: username"></strong> is already in use.
</p>
</li>
</ul>
<button data-bind="enable: canSave, click: save">save</button>
<p data-bind="visible: isEmpty">
Before you can save, you need to add at least one account.
</p>
<p data-bind="visible: !isValid()">
Please review your entries before you can save.
</p>
I'm writing a fairly complicated search form in Angular.
The form is broken into sections - you can search by ID, url, text string or location. When you search by text string and location at the same time, I need to validate that you submit latitude and longitude together.
In other words, searching by a text string is fine. Searching by lat / lng is fine. Searching by a text string and latitude but omitting longitude is not ok.
Whenever possible, I'm using HTML5 and angular directives for validating individual fields' contents, but I'm trying to validate a particular combination of values by using a scope watcher, looking at the form object, and using $setValidity() if I discover that the current search mode is incompatible with a particular combination of fields.
My current issue is that, once I've used $setValidity() once, that validation state is "stuck". When the user switches out of 'textOrLocation' search mode, I want to let angular go back to its default validation behavior. I don't understand why it's not doing that - I only call $setValidity() on scope change after checking the form's in 'textOrLocation' mode.
Javascript:
$scope.search = {
mode: 'id'
};
$scope.$watch(textOrLocationValid, function() {});
function textOrLocationValid() {
var usingTextOrLocation = $scope.search.mode == 'textOrLocation';
if (usingTextOrLocation) {
var textModel = $scope.form.searchText || {},
textValid = textModel.$valid,
textValue = textModel.$modelValue,
latModel = $scope.form.searchLat || {},
latValid = latModel.$valid,
latValue = latModel.$modelValue,
lngModel = $scope.form.searchLng || {},
lngValid = lngModel.$valid,
lngValue = lngModel.$modelValue,
formValid = (textValid && latValid && lngValid) && // No invalid fields
((latValue && 1 || 0) + (lngValue && 1 || 0) != 1) && // Either both lat and long have values, or neither do
(textValue || latValue); // Either text or location are filled out
if (formValid) {
// Explicitly set form validity to true
$scope.form.$setValidity('textOrLocation', true);
} else {
// Explicitly set form validity to false
$scope.form.$setValidity('textOrLocation', false);
}
}
}
HTML
<form name="form">
<div ng-if="search.mode == 'id'">
<input type="text" name="searchId" required>
</div>
<div ng-if="search.mode == 'textOrLocation'">
<input type="text" name="searchText">
<input type="number" name="searchLat" min="-90" max="90" step="0.000001">
<input type="number" name="searchLng" min="-180" max="180" step="0.000001">
</div>
<button ng-disabled="form.$invalid">Submit</button>
</form>
My understanding is that because the function is being watched, it's actually being evaluated by Angular periodically during each digest. A simple solution might be to set the validity of textOrLocation to true when that particular form is not in focus. This would allow the button state to depend on the validity of the field in the id form.
function textOrLocationValid() {
var usingTextOrLocation = $scope.search.mode == 'textOrLocation';
if (usingTextOrLocation) {
var textModel = $scope.form.searchText || {},
textValid = textModel.$valid,
textValue = textModel.$modelValue,
latModel = $scope.form.searchLat || {},
latValid = latModel.$valid,
latValue = latModel.$modelValue,
lngModel = $scope.form.searchLng || {},
lngValid = lngModel.$valid,
lngValue = lngModel.$modelValue,
formValid = (textValid && latValid && lngValid) && // No invalid fields
((latValue && 1 || 0) + (lngValue && 1 || 0) != 1) && // Either both lat and long have values, or neither do
(textValue || latValue); // Either text or location are filled out
if (formValid) {
// Explicitly set form validity to true
$scope.form.$setValidity('textOrLocation', true);
} else {
// Explicitly set form validity to false
$scope.form.$setValidity('textOrLocation', false);
}
}
else{
// Explicitly set form validity to true because form is not active
$scope.form.$setValidity('textOrLocation', true);
}
}
To create complex tests, you can use a small directive use-form-error, which may also be useful to you in the future.
With this directive, you can write:
<div ng-form="myForm">
<div>
<input type="text" ng-model="searchText" name="searchText">
<input type="number" ng-model="searchLat" name="searchLat" min="-90" max="90" step="0.000001">
<input type="number" ng-model="searchLng" name="searchLng" min="-180" max="180" step="0.000001">
<span use-form-error="textOrLocation" use-error-expression="textOrLocationValid()" use-error-input="myForm"></span>
</div>
{{myForm.$error}}
<br>
<button ng-disabled="myForm.$invalid">Submit</button>
</div>
And JS
angular.module('ExampleApp', ['use']).controller('ExampleController', function($scope) {
$scope.search = {
mode: 'textOrLocation'
};
$scope.textOrLocationValid = function() {
var usingTextOrLocation = $scope.search.mode == 'textOrLocation';
if (usingTextOrLocation) {
var textModel = $scope.myForm.searchText || {},
textValid = textModel.$valid,
textValue = textModel.$modelValue,
latModel = $scope.myForm.searchLat || {},
latValid = latModel.$valid,
latValue = latModel.$modelValue,
lngModel = $scope.myForm.searchLng || {},
lngValid = lngModel.$valid,
lngValue = lngModel.$modelValue,
formValid = (textValid && latValid && lngValid) && // No invalid fields
((latValue && 1 || 0) + (lngValue && 1 || 0) != 1) && // Either both lat and long have values, or neither do
(textValue || latValue); // Either text or location are filled out
return !formValid;
} else {
// Explicitly set form validity to true because form is not active
return false;
}
}
});
Live example on jsfiddle:
I got it working, you can find code in this Plunker
There were several problems (I'm making assumption, you are trying handling your form in controller, not in custom directive):
$scope.form that we are trying to access in controller is not same form that we have in the view. Form gets its own scope. which is not directly accessible in controller. To fix this, we can attach form to $scope.forms - object, that is declared in controller (read more on inheritance patterns here)
we should attach ng-model to inputs, so we can $watch them, since it not possible to watch form directly (read more here)
in addition, we have to watch $scope.search changes.
It's definitely not the most elegant solution to handle custom validation... Will try to come up with custom directive for that.
I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>
I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}
I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/