Javascript is only validating the first variable and ignoring my others - javascript

Trying to make an address book for school and entered two fields and having validation. It seems like it's only validating the first field which is the name and ignoring the rest? I'm not sure if I have something wrong? It keeps displaying not a valid name as the error message and nothing else.
var validate_birthdate = my.isBirthdateBad(add_birthdate);
if (!valid_name.test(add_name)) {
alert("not a valid name");
valid_contact = false;
} else if (add_address.length > 0) {
if (!valid_address.test(add_address)) {
alert("not a valid address: " + add_address);
valid_contact = false;
}
} else if (add_birthdate.length > 0) {
if (!valid_birthdate.test(add_birthdate)) {
alert("not a valid birthdate");
valid_contact = false;
}
} else if (add_gender.length > 0) {
if (!valid_gender.test(add_gender)) {
alert("not a valid gender");
valid_contact = false;
}
} else if (add_ocupation.length > 0) {
if (!valid_occupation.test(add_occupation)) {
alert("not a valid job title");
valid_contact = false;
}
} else if (validate_birthdate) {
alert("not a valid birthdate: " + validate_birthdate);
valid_contact = false;
} else if (!(add_photo !== undefined) &&
(add_photo.length > 0) &&
(add_photo.indexOf("data:image/jpeg") === 0)) {
alert("image is not a jpeg!");
valid_contact = false;
}
// note the use of the "anonymous" function
// this returns an array of all of the matched contacts! Powerful!
var exists = _address_book_contacts.filter(function (contact) {
//check to see if the current "add_name"
// is found in the address book!
return contact.name() === add_name;
});
if (exists && (exists.length > 0)) {
if (!confirm("WARNING: " +
add_name +
" exists in database. " +
"Would you like to add again?")) {
valid_contact = false;
}
}

Related

JavaScript - While loop statement prints out multiple times

I am unable to print a single output statement when there is no match. At the moment, if there is no match (no number incl. in password) it will print out multiple times until it does find a match.
Could anyone take a look at my dilemma below please:
var password = "password1";
var i = 0;
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
while (i < password.length) {
if (password[i] == password.match(/[0-9]/g)) {
console.log("found: " + password[i]);
} else {
console.log("not found");
}
i++;
}
}
}
var password = "password1";
var i = 0;
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
var found = false;
while (i < password.length) {
if (password[i].match(/[0-9]/g)) {
found = true;
break;
}
i++;
}
if(found) {
console.log("found");
} else {
console.log("not found");
}
}
}
But, if you are only looking for a number in the string, you should better do it like this:
var password = "password1";
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else if(!password.match(/[0-9]{1,}/)) {
console.log("password should contain at least one number");
} else {
console.log("okay");
}
}
Here is a JSFiddle: https://jsfiddle.net/7btt1axb/
Something like this?
var password = "password1";
function checkPassword(password) {
if (password === "") {
console.log("password cannot be empty");
} else if (password.length < 8) {
console.log("password should be at least 7 characters");
} else {
var i = 0, found = false;
while (i < password.length && !found) {
if (password[i] == password.match(/[0-9]/g)) found = true;
else i++;
}
if (found) {
console.log("found: " + password[i]);
} else console.log("not found");
}
}
checkPassword(password);

show multiple alert in one message in jquery

I have multiple required field controls on my aspx form.
Now what I want is to show the validation message on button click if anything is not filled or checked.
I want it on one message in JQuery.
Here is my JQuery code:-
$(document).ready(function () {
$('#btnSave').click(function (e) {
if (!validateTitle() || !validatePrefix() || !validateTextBoxes()) {
e.preventDefault();
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
alert("Please enter the text in other title");
return false;
}
return true;
} else {
alert('Please select the title');
return false;
}
}
function validatePrefix() {
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
alert("Please enter the text in other prefix");
return false;
}
return true;
} else {
alert('Please select the prefix');
return false;
}
}
function validateTextBoxes() {
if ($("#txtFirstName").val() === "") {
alert('First name is required');
return false;
}
if ($("#txtMiddleName").val() === "") {
alert('Middle name is required');
return false;
}
if ($("#txtLastName").val() === "") {
alert('Last name is required');
return false;
}
if ($("#txtFatherName").val() === "") {
alert('Father name is required');
return false;
}
if ($("#txtCurrentCompany").val() === "") {
alert('Current company is required');
return false;
}
if ($("#txtDateofJoin").val() === "") {
alert('Date is required');
return false;
}
if ($("#txtCurrentExp").val() === "") {
alert('Current Experience is required');
return false;
}
return true;
}
});
Try below code
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTitle();
validatePrefix();
validateTextBoxes();
if(ErrArr.length > 0) {
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
ErrArr.push("Please enter the text in other title");
}
} else {
ErrArr.push('Please select the title');
}
}
function validatePrefix() {
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
ErrArr.push("Please enter the text in other prefix");
}
} else {
ErrArr.push('Please select the prefix');
}
}
function validateTextBoxes() {
if ($("#txtFirstName").val() === "") {
ErrArr.push('First name is required');
}
if ($("#txtMiddleName").val() === "") {
ErrArr.push('Middle name is required');
}
if ($("#txtLastName").val() === "") {
ErrArr.push('Last name is required');
}
if ($("#txtFatherName").val() === "") {
ErrArr.push('Father name is required');
}
if ($("#txtCurrentCompany").val() === "") {
ErrArr.push('Current company is required');
}
if ($("#txtDateofJoin").val() === "") {
ErrArr.push('Date is required');
}
if ($("#txtCurrentExp").val() === "") {
ErrArr.push('Current Experience is required');
}
}
});
Instead of using alert all the time, save the message to a variable instead.
Then alert that message after all tests are done.
$(document).ready(function () {
var message = "";
$('#btnSave').click(function (e) {
message = "";
if (!validateTitle() || !validatePrefix() || !validateTextBoxes()) {
e.preventDefault();
alert(message);
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
message += "Please enter the text in other title\n";
return false;
}
return true;
} else {
message += 'Please select the title\n';
return false;
}
}
....
});
Use the following fiddle [JSFiddle][1] , this will basically push all the error messages into an array and can show the results.
Please update if this works for you as i am not aware of markup
Just a simple trick you can do
just use a string variable for messages appending and counter.
$(document).ready(function () {
var Messages;
var counter=0;
$('#btnSave').click(function (e) {
validateTitle();
validatePrefix();
validateTextBoxes();
if(counter > 0)
{
alert(Messages);
e.preventDefault();
counter=0;
}
});
function validateTitle() {
debugger;
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
Messages += "Please enter the text in other title";
Messages += "\n";
counter ++;
}
} else {
Messages += 'Please select the title';
Messages += "\n";
counter ++;
}
}
function validatePrefix() {
debugger;
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
Messages += "Please enter the text in other prefix";
Messages += "\n";
counter ++;
}
} else {
Messages += 'Please select the prefix';
Messages += "\n";
counter ++;
}
}
function validateTextBoxes() {
debugger;
if ($("#txtFirstName").val() === "") {
Messages += 'First name is required';
Messages += "\n";
counter ++;
}
if ($("#txtMiddleName").val() === "") {
Messages += 'Middle name is required';
Messages += "\n";
counter ++;
}
if ($("#txtLastName").val() === "") {
Messages += 'Last name is required';
Messages += "\n";
counter ++;
}
if ($("#txtFatherName").val() === "") {
Messages += 'Father name is required';
Messages += "\n";
counter ++;
}
if ($("#txtCurrentCompany").val() === "") {
Messages += 'Current company is required';
Messages += "\n";
counter ++;
}
if ($("#txtDateofJoin").val() === "") {
Messages += 'Date is required';
Messages += "\n";
counter ++;
}
if ($("#txtCurrentExp").val() === "") {
Messages += 'Current Experience is required';
Messages += "\n";
counter ++;
}
}
});
Just update counter and impliment check if check > 0 show message
(alert)
it will benefit you two things
User dont need to click each time and get alert.. dont need to
return false.user Must know at once what erors are in form.
Secondly code is simple/Simple logic.
Try this.
$(document).ready(function () {
var Errors = [];
$('#btnSave').click(function (e) {
if (!validateTitle() || !validatePrefix() || !validateTextBoxes()) {
if(Errors.length > 0) {
alert(Errors.join("\n"));
}
e.preventDefault();
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
Errors.push("Please enter the text in other title");
}
return true;
} else {
Errors.push('Please select the title');
}
}
function validatePrefix() {
if ($("#ddlPrefix").val() > "0") {
if ($("#ddlPrefix").val() == "1110" && $("#txtPrefix").val() === "") {
Errors.push("Please enter the text in other prefix");
}
return true;
} else {
Errors.push('Please select the prefix');
}
}
function validateTextBoxes() {
if ($("#txtFirstName").val() === "") {
Errors.push('First name is required');
}
if ($("#txtMiddleName").val() === "") {
Errors.push('Middle name is required');
}
if ($("#txtLastName").val() === "") {
Errors.push('Last name is required');
}
if ($("#txtFatherName").val() === "") {
Errors.push('Father name is required');
}
if ($("#txtCurrentCompany").val() === "") {
Errors.push('Current company is required');
}
if ($("#txtDateofJoin").val() === "") {
Errors.push('Date is required');
}
if ($("#txtCurrentExp").val() === "") {
Errors.push('Current Experience is required');
}
return true;
}
});
Add perfect separation in each message to differentiate it.

How do I correctly perform form validation in JavaScript?

I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}

Javascript: Validation alerts 2

My goal is this:
Check if email and name are empty. If so, give 'Enter email or name' alert.
If they do, check for an # in email If none is found, give 'Bad email' alert.
Check if email and name contain any letters, if they do, give 'Success' alert
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");}
return false;
if(email.indexOf("#") == -1){
alert("Bad email");}
return false;
var a = email.length;
var b = name.length;
if(a==>0, b==>0){
alert("Message sent");}
return true;
}
This is what I've come up with so far, but it isn't working. I'm quite new at javascript so maybe you guys could tell me what I've done wrong?
The problem you're having is the close bracket is in the wrong place. You have it at the end of your alert statement and you probably want the return to be included with your if statement. if this is the case then change it to be:
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");
return false;
}
if(email.indexOf("#") == -1){
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if(a > 0 && b > 0){
alert("Message sent");
return true;
}
}
A better way to do the same thing would be because that way you're not checking the variables for length and size twice:
function test(email, name) {
var a = email.length;
var b = name.length;
if ( a > 0 && b > 0 ) {
// ignore 0 because email addresses shouldn't start with #
if ( email.indexOf("#") > 0 ) {
alert("Message sent");
return true;
}
else {
alert("Bad email");
return false;
}
}
else {
alert("Enter mail or name");
return false;
}
}
Try this JSFiddle that seems to fit your needs http://jsfiddle.net/9nF5W/
function test(email, name) {
if (email == "" || name == "") {
alert("Enter mail or name");
return false;
}
if (email.indexOf("#") == -1) {
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if (a > 0 && b > 0) {
alert("Message sent");
}
return true;
}
test('tes#t', 'test');
I think there is an other mistake than the returns statements in "if(a==>0, b==>0){" by the way.

Date Validation not working using JavaScript

I have two two date fields - from date and to date, and i need to validate 3 things
Both the values are entered or not
Date datatype check
To date must be greater than from date.
But my script is not working.
can some body please check?
Thanks
function checkBothDates(sender,args)
{
var from = document.getElementById(sender.From);
var to = document.getElementById(sender.To);
var behaviorId = sender.behavior;
var from_value = from.value;
var to_value = to.value;
if((from_value == "")&&(to_value == ""))
{
args.IsValid = true;
}
else
{
if((from_value != "")&&(to_value != ""))
{
if((isValidDate(from_value))&&(isValidDate(to_value)))
{
if(from_value < to_value)
{
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please enter valid dates in both the fields";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please make sure you enter both the values";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
}
function isValidDate(val)
{
var format = 'dd/MM/yyyy'
var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!regexp.test(val))
{
return false;
}
else
{
try
{
$.datepicker.parseDate(format,val,null);
return true;
}
catch(Error)
{
return false;
}
}
}
Your code is pretty repetitive, you can shorten a lot of it.
Also note that the regex check is entirely unnecessary, since $.datepicker.parseDate() won't accept anything invalid anyway.
function checkBothDates(sender, args) {
var from = parseDate( $(sender.From).val() ),
to = parseDate( $(sender.To).val() );
args.IsValid = false;
if (from == "" && to == "" || from && to && from <= to) {
args.IsValid = true;
} else if (from == null || to == null) {
sender.errormessage = "Please enter valid dates in both the fields";
} else if (from > to) {
sender.errormessage = "To date must be greater than or equal to the from date";
} else {
sender.errormessage = "Please make sure you enter both the values";
}
if (!args.IsValid && sender.behavior) {
openCollapsiblePanel(sender.behavior);
}
}
function parseDate(val) {
if (val == "") return "";
try {
return $.datepicker.parseDate('dd/MM/yyyy', val);
} catch (ex) {
return null;
}
}
There is a problem in your code aroun the 19th line. You wrote:
if(from_value < to_value) {
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
But you definitely want that from_value is smaller then to_value. Fix it!

Categories