I made my own form validation just for 2 inputs, one is for Phone number and another one for Email address. and also I have 2 forms in 1 page.
my code is
var email, phone;
if (email address validation passed) {
email = true;
} else {
email = false;
}
if (phone number validation passed) {
phone = true;
} else {
phone = false;
}
if (!(phone && email)) {
return false
} else {
return true
}
as I have two forms on the same page, I'd like to have another snippet for the 2nd form like,
var email2, phone2;
if (email address validation passed) {
email2 = true;
} else {
email2 = false;
}
if (phone number validation passed) {
phone2 = true;
} else {
phone2 = false;
}
if (!(phone2 && email2)) {
return false
} else {
return true
}
the issue I found is that, for getting the form submitted I need to have email, phone, email2, phone2; all equal to true. however, I need to submit in condition if email, phone are true or phone2, email2 are true
Just need someone to check if this is a right logical way to solve my problem?
if (!(phone2 && email2)) {
return false
} else if(!(phone && email )) {
return false
} else return true;
however, I need to submit in condition if email, phone are true or phone2, email2 are true
The way you said it there is the easiest way to code it:
if ((email && phone) || (email2 && phone2)) {
return true;
} else {
return false;
}
And if you are just going to return true or false based on whether a condition is true or false, you can do it in one line like this:
return (email && phone) || (email2 && phone2);
You can check it like
if((phone2 && email2) || (phone && email))
return true;
else
return false;
Related
I was wondering if there was anyway of simplifying the code below without using jQuery?
Still very inexperienced with JavaScript so any help is much appreciated! Thank you in advance everyone :D
if (name === "") {
document.getElementById("name").focus();
alert("Name must be filled out.");
return false;
} else if (!(/\S/.test(name))) {
document.getElementById("name").focus();
alert("Name cannot be blank.");
return false;
} else if (!(/^([^0-9]*)$/.test(name))) {
document.getElementById("name").focus();
alert("Name cannot contain numbers.");
return false;
} else if (email === "") {
document.getElementById("email").focus();
alert("Please enter your email address.");
return false;
} else if (/^\S+#\S+\.\S+$/.test(email) === false) {
document.getElementById("email").focus();
alert("Please enter a valid email address.");
return false;
} else if (basecamp === "") {
document.getElementById("basecamp").focus();
alert("Please select a base camp.");
return false;
} else if (max == 0) {
document.getElementById("basecamp").focus();
alert("This base camp has run out of slots, please select another base camp.");
return false;
} else if (package === "") {
document.getElementById("package").focus();
alert("Please select a package.");
return false;
} else if (validdate === "") {
document.getElementById("date").focus();
alert("Please select a date.");
return false;
} else if (groupsize === "") {
document.getElementById("groupsize").focus();
alert("Please select a group size.");
return false;
} else if (groupsize <= 0) {
document.getElementById("groupsize").focus();
alert("Please select a postitve number.");
return false;
} else {
updateData();
}
}
You might use an array of conditions, where each subarray (or subobject) contains the condition to test (what's in your if / else if at the moment), the ID to focus if the condition is true, and the message to alert. Then, iterate over it, finding the first truthy condition - if found, alert the associated message, focus the element, and return false. Otherwise, if none of the bad conditions were found, call updateData:
const arr = [
[
name === "",
'name',
"Name must be filled out."
],
[
!(/\S/.test(name)),
'name',
'Name cannot be blank.'
],
[
!(/^([^0-9]*)$/.test(name)),
'name',
'Name cannot contain numbers.'
]
// etc
];
const firstBadCondition = arr.find(([cond]) => cond);
if (firstBadCondition) {
const [, idToFocus, errorMessage] = firstBadCondition;
document.getElementById(idToFocus).focus();
alert(errorMessage);
return false;
} else {
updateData();
}
You can create a function which takes element id name,email... as parameter and a message that need to alert. return false from that function. And you if-else statements just return that function.
Here is a little example.
function sendMsg(elm,msg){
document.getElementById(elm).focus();
alert(msg)
return false;
}
if (name === "") {
return sendMsg('name',"Name must be filled out.")
} else if (!(/\S/.test(name))) {
return sendMsg("name","Name cannot be blank.")
} else if (!(/^([^0-9]*)$/.test(name))) {
return sendMsg('name',"Name cannot contain numbers.")
} else if (email === "") {
return sendMsg('email',"Please enter your email address.")
} else if (/^\S+#\S+\.\S+$/.test(email) === false) {
return sendMsg('email',"Please enter a valid email address.")
}
.....
.....
.....
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.
As a new guy in javascript am trying to create a script which is supposed to validate a registration form. Simple things, if 1 field is empty, throw the appropriate message. I succesfully managed it following the tutorials on the internet, it works the way i want it, database doesn't get updated when 1 field is empty.
However there is a problem. When ALL fields are empty the script somehow fails to notice this and proceeds with the registration perfectly.
My script is the following:
function validateForm()
{
var a=document.forms["Registration_Form"]["fname"].value;
var b=document.forms["Registration_Form"]["lname"].value;
var c=document.forms["Registration_Form"]["email"].value;
var d=document.forms["Registration_Form"]["username"].value;
var e=document.forms["Registration_Form"]["password"].value;
if ((a==null || a=="") && (b==null || b=="") && (c==null || c=="") && (d==null || d=="") && (e==null || e==""))
{
alert("All Field must be filled out");
return false;
}
if (a==null || a=="")
{
alert("First name must be filled out");
return false;
}
if (b==null || b=="")
{
alert("Last name must be filled out");
return false;
}
if (c==null || c=="")
{
alert("email adress must be filled out");
return false;
}
if (d==null || d=="")
{
alert("Username must be filled out");
return false;
}
if (e==null || e=="")
{
alert("Password must be filled out");
return false;
}
}
This is drilling through my brain and driving me crazy for hours.
When 1 field is completed and the rest are missing i get the appropriate message for the first missing field and all good, registration is prevented.
But when all are missing, it just doesn't happen, registration is succesfull and enters all blank fields on my database.
I can't understand, it's here, right?
if ((a==null || a=="") && (b==null || b=="") && (c==null || c=="") && (d==null || d=="") && (e==null || e==""))
{
alert("All Field must be filled out");
return false;
}
If fname is empty AND lname is empty AND email is empty AND username is empty AND password is empty, alert and return false.
I don't understand, how can there be a problem in something so simple? What am i missing?
And even if this line didn't existed, shouldn't the script get caught in the remaining if's that have only 1 clause and give the false there?
I would try it like this. You shouldn't need to check them all at once...
function validateForm()
{
var a=document.forms["Registration_Form"]["fname"].value;
var b=document.forms["Registration_Form"]["lname"].value;
var c=document.forms["Registration_Form"]["email"].value;
var d=document.forms["Registration_Form"]["username"].value;
var e=document.forms["Registration_Form"]["password"].value;
try {
if ((a === '') || (a === null)) {
throw new Error('First name must be filled out');
}
if ((b === '') || (b === null)) {
throw new Error('Last name must be filled out');
}
if ((c === '') || (c === null)) {
throw new Error('email adress must be filled out');
}
if ((d === '') || (d === null)) {
throw new Error('Username must be filled out');
}
if ((e === '') || (e === null)) {
throw new Error('Password must be filled out');
}
return true;
}
catch (formError) {
alert(formError.message);
return false;
}
}
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.
I have variable deleteboxvalue
var deleteboxvalue = "111111111111111";
if(deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected."); return true;
}
I want to check if 0 is not exist in this I want to return false and alert as "You can't delete all Contact Number." but in both cases if 0 exist in variable in that case also its returning false and giving me alert as "You can't delete all Contact Number."
I want to check if 0 is not exist in this I want to return false
If that's the case then you've got your logic reversed. You are currently returning false if 0 is in the string (i.e. it is found at an index greater than or equal to 0). If you want to return false when 0 is not found in the string, you can do this:
if(deleteboxvalue.indexOf('0') == -1) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected.");
return true;
}
However, I may have completely misunderstood what you're trying to do...
Create a function in JavaScript such as:
function CheckContacts() {
var deleteboxvalue = "111111111111111";
if (deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
} else {
alert("All Zeros are not selected."); return true;
}
}
and
On body onload call that JavaScript method:
<body onload="CheckContacts()">