Problem with form validation (phone numbers) - javascript

Ok, I have a validation script that checks everything on the form - but it flags the phone number fields as wrong regardless of whats in there. I've tried it a couple different ways and I cant figure out what I am doing wrong.
The part of the script that validates is...
if (testPattern(phone1, /^\d{3}$/)== false) { // checking phone length
valid = false;
}
if (testPattern(phone2, /^\d{3}$/)== false) {
valid = false;
}
if (testPattern(phone3, /^\d{4}$/)== false) {
valid = false;
}
The function code is...
function testPattern(field, reg2) {
var trueOrfalse = reg2.test(field)
if (trueOrfalse == false) {
field.style.backgroundColor="yellow"; // if false, change colors and return false
field.style.color="red";
return false;
}
else {
field.style.backgroundColor="white"; // if true, change colors and return true
field.style.color="black";
return true;
}
}

Maybe
var trueOrfalse = reg2.test(field)
should be
var trueOrfalse = reg2.test(field.value)
Added:
Also, remember that you don't have to compare to true or false when evaluating in a boolean context. (Use the value itself or the negation). And it is better to name variables after their meaning, not "trueorfalse" Here's my re-write:
if (!testPattern(phone1, /^\d{3}$/)) { // checking phone length
valid = false;
}
if (!testPattern(phone2, /^\d{3}$/)) {
valid = false;
}
if (!testPattern(phone3, /^\d{4}$/)) {
valid = false;
}
function testPattern(field, reg2) {
var good = reg2.test(field.value);
if (good) {
field.style.backgroundColor="white"; // if good, change colors
field.style.color="black";
}
else {
field.style.backgroundColor="yellow"; // if bad, change colors
field.style.color="red";
}
return(good);
}

Not an actual answer to your question, since there's nothing inherently wrong with the snippets you posted, but this was too large for a comment.
Your code is really redundant!
You could express the whole first part as:
valid = testPattern(phone1, /^\d{3}$/) &&
testPattern(phone2, /^\d{3}$/) &&
testPattern(phone3, /^\d{4}$/)
And the function code as:
function testPattern(field, reg2) {
var test_result = reg2.test(field)
if (test_result) {
field.style.backgroundColor = "white";
field.style.color = "black";
} else {
field.style.backgroundColor = "yellow";
field.style.color = "red";
}
return test_result;
}
Or even more concise:
function testPattern(field, reg2) {
var test_result = reg2.test(field)
field.style.backgroundColor = test_result ? "white" : "yellow";
field.style.color = test_result ? "black" : "red";
return test_result;
}
Isn't that much easier to read?

Related

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

Changing the boolean value of an object stored in array

I'm just starting my journey with JS so pleace be patient :)
I'm building a small app. The images on the left side are stored in an array. If someone clicks one of them I want to change its height but also the boolean value from false to true so that I know which one the user clicked (for further purposes). In my mind it goes like this: creating an array->add EventListener to the item->chain it witch the function choosen(change the value to true)->run setClick function that changes the height. What's wrong there?
I aprecciate any advice.
CODEPEN http://codepen.io/finewitch/pen/ZBKMKm
var storage = new Array();
storage[0] = document.getElementById("grandFatherCh");
storage[1] = document.getElementById("grandMotherCh");
storage[2] = document.getElementById("sisterCh");
storage[3] = document.getElementById("brotherCh");
storage[4] = document.getElementById("fatherCh");
storage[5] = document.getElementById("motherCh");
storage[0].clicked = false;
storage[1].clicked = false;
storage[2].clicked = false;
storage[3].clicked = false;
storage[4].clicked = false;
storage[5].clicked = false;
for (var i=0; i<storage.length; i++){
storage[i].addEventListener("click",choosen, setClick);
console.log("clicked");
};
function choosen(){
if (storage[i].clicked == false)
{
return "stillFalse"
storage[i].clicked = true;
}
};
function setClick(){
if(storage[i].clicked === true){
return "setClickWorks"
storage[i].style.height = "400px";
}else{
console.log('failed');
}
};
Maybe I'm missing something but I think you have the return statement in the wrong place no? Should be
function choosen(){
if (storage[i].clicked == false) {
return "stillFalse"
} else {
storage[i].clicked = true;
}
}
function setClick(){
if (storage[i].clicked === true){
storage[i].style.height = "400px";
return "setClickWorks"
} else {
console.log('failed');
}
}

phone number validation wont pass

function ClientContactCheck(){
var clientcontact = $("#client_contact_id").val();
if(clientcontact.length != ""){
if(!isNaN(clientcontact)){
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
}
}else{
$("#client_contact_id").css('border-color', "red");
}
return false;
}
i am using this function to validation phone number , my intention is simple just not be empty and must be number.
but if put !isNaN and my input was 123-456-789 , it wont valid cause the - was not a number, how to i make my function bypass the - ?
so if the input value had - it will pass thought.
thank
You can use :
str.replace("-", "");
and then check your input if it is a number only.
Edit:
var res = str.replace(/\-/g,'');
You can check it with a regular expression:
var clientcontact = $("#client_contact_id").val();
if (/^[0-9\-]+$/.test(clientcontact)) {
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
} else {
$("#client_contact_id").css('border-color', "red");
return false;
}
This will allow '-', '--', '---' too. If that is not desired, you can do one more check: ... && !/^-*$/.test(clientcontact)
You can do something like this to validate the phone number.
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
More at http://www.w3resource.com/javascript/form/phone-no-validation.php

Validate forms using javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

Javascript IF blocks get skipped

I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.

Categories

Resources