At least one of two fields must be completed validation - javascript

First of all, I am not using jquery validation plugin.
I have the following validation in JavaScript:
var m = mob.substr(0,2);
var l = land.substr(0,2);
if (mob == '' && land == '') {
alert("You must enter at least one phone number");
return false;
}
else if (mob.length != 10 || m != "04") {
alert("Mobile number is invalid. Must be a valid australian mobile number.");
return false;
}
else if (land.length != 10 || l == "04" || l == "01" || l == "05" || l == "06" || l == "09" || l == "00") {
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}
As the title suggests, I want the user to be able to input just one or both of the fields but not leave both blank.
How can I incorporate this into the validation?

var m = mob.substr(0,2);
var l = land.substr(0,2);
if (mob === '' && land === '') {
alert("You must enter at least one phone number");
return false;
}
if (mob !== '' && (mob.length !== 10 || m !== "04")) {
alert("Mobile number is invalid. Must be a valid australian mobile number.");
return false;
}
if (land !== '' && (land.length !== 10 || l === "04" || l === "01" || l === "05" || l === "06" || l === "09" || l === "00")) {
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}
return true;
Here just add one more condition to the last two conditions. And make them as independent if statements. So all of them will be evaluated.

Just an idea...
function validate () {
var sMobile = ...;
var sLand = ...;
var lines = parsePhoneLines(sMobile, sLand);
if (lines.errors) {
for (var i = 0, length = lines.errors.length; i < length; i++) {
alert (lines.errors[i]);
}
return false;
} else {
return true;
}
}
function parsePhoneLines (sMobile, sLand) {
var mobile = parseMobile(sMobile),
land = parseLand(sLand);
if (mobile.errors && land.errors) {
return {
errors: mobile.errors.concat(land.errors)
};
} else {
return {
land: land.value,
mobile: mobile.value
};
}
}
function parseMobile (s) {
var errors = getErrorsForMobile(s);
if (errors.length === 0) {
return { value: s };
} else {
return { errors: errors };
}
}
function parseLand (s) {
var errors = getErrorsForLand(s);
if (errors.length === 0) {
return { value: s };
} else {
return { errors: errors };
}
}

Try this:
var m = mob.substr(0,2);
var l = land.substr(0,2);
if (mob == '' && land == '') {
alert("You must enter at least one phone number");
return false;
} else {
if (mob != '') {
if (mob.length != 10 || m != "04") {
alert("Mobile number is invalid. Must be a valid australian mobile number.");
return false;
}
} else {
if (land.length != 10 || l == "04" || l == "01" || l == "05" || l == "06" || l == "09" || l == "00") {
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}
}
}
return true;
Just need an else clause to the first if.

var m = mob.substr(0,2);
var l = land.substr(0,2);
var flag=1;
if (mob == '' && land == '') {
alert("You must enter at least one phone number");
return false;
}
else if (mob.length != 10 || m != "04") {
if(land.length>0)
{
//landline have value don not alert this
}
else
{
alert("Mobile number is invalid. Must be a valid australian mobile number.");
flag=0;//means invalid
}
}
else if (land.length != 10 || l == "04" || l == "01" || l == "05" || l == "06" || l == "09" || l == "00") {
if(flag==1)
{
return true;// means mobile have value
}
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}

Related

JavaScript Form Validation not working using isNaN

I have changed my code and added the isNaN to make sure a credit card validation is checking that only numbers are entered, however it broke the code.
Note this is only a code snippet of the broken code.
Tried adding backets and moving around code.
var american = document.getElementById("americanInput").value;
var master = document.getElementById("masterInput").value;
var visa = document.getElementById("visaInput").value;
var email = document.getElementById("email").value;
var errMsg = document.getElementById("errMsg");
var postcode = document.getElementById("billingPostcode").value;
var address = document.getElementById("billingAddress").value;
var suburb = document.getElementById("billingSuburb").value;
} else if (master.length > 0 && master.length !== 16 && isNaN(master)||
visa.length > 0 && visa.length !== 16 && isNaN(visa)||
american.length > 0 && american.length !== 15 && isNaN(american)){
errMsg.innerHTML = "Please check your card details again";
return false;
} else if (postcode.length < 4 || (!postcode.match(/^[0-9]*$/))) {
errMsg.innerHTML = "Please enter a valid postcode";
return false;
} else if (suburb.length < 8 || address.length < 8) {
errMsg.innerHTML = "Please check your address, to confirm details"
return false;
}
The code should validate and give an error message.
Try the below code. I have used 'OR' condition with isNaN instead of 'AND' condition. I assume you are checking for the credit card value is not null/undefined in your code. If not you need to check to make sure the below code works.
var american = document.getElementById("americanInput").value;
var master = document.getElementById("masterInput").value;
var visa = document.getElementById("visaInput").value;
var email = document.getElementById("email").value;
var errMsg = document.getElementById("errMsg");
var postcode = document.getElementById("billingPostcode").value;
var address = document.getElementById("billingAddress").value;
var suburb = document.getElementById("billingSuburb").value;
if ((master.length > 0 && (master.length !== 16 || isNaN(master))) ||
(visa.length > 0 && (visa.length !== 16 || isNaN(visa))) ||
(american.length > 0 && (american.length !== 15 || isNaN(american)))) {
alert("Please check your card details again");
return false;
} else if (postcode.length < 4 || (!postcode.match(/^[0-9]*$/))) {
alert("Please enter a valid postcode");
return false;
} else if (suburb.length < 8 || address.length < 8) {
alert("Please check your address, to confirm details");
return false;
}

my code could not able to detect undefined and null values can someone please correct it?

var isTopper = false
var marksobtained = window.prompt('please enter the marks obtained ')
if (marksobtained == undefined || marksobtained == null || marksobtained == '') {
alert('invalid')
} else if (marksobtained < 0 || marksobtained > 100) {
alert('enter between 0 to 100')
} else {
marksobtained = Number(marksobtained)
var totalmarks = 100
var percentage = (marksobtained / totalmarks) * 100
if (percentage > 90) {
isTopper = true
} else {
isTopper = false
}
alert(isTopper)
}
I don't why your code is not working for you(as it is working for us), I just made few modifications in your code like replace if (marksobtained == undefined || marksobtained == null || marksobtained == '') this with this if (!marksobtained) and
As you are asking only one subject marks you don't have to calculate percentage you can directly tell on the basis of marks whether he/she is topper or not(I am saying this only because you are asking only one subject marks and that marks is in between 1 to 100)
var isTopper = false
var marksobtained = window.prompt('please enter the marks obtained ')
if (!marksobtained || isNaN(marksobtained)) {
alert('invalid')
} else if (marksobtained < 0 || marksobtained > 100) {
alert('enter between 0 to 100')
} else {
marksobtained = Number(marksobtained);
if (marksobtained > 90) {
isTopper = true
} else {
isTopper = false
}
alert(isTopper)
}
I dont know where is your problem. Please provide some details. alert('invalid') is working correctly and being called when value is empty string.
Instead of
if (marksobtained == undefined || marksobtained == null || marksobtained == '')
You can simply use
if (!marksobtained) { ...

HTML Form won't submit after validaiton with Javascript

I have questions regarding form submitting in HTML with Javascript.
My Javascript is as follows:
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
alert("Your name cannot be blank");
}
if (b == null || b == "") {
alert("Enter a valid email address.");
}
if (c == null || c == "") {
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
alert("Must select an Issue.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (g == null || g == "") {
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
alert("Preferred time must follow the format set.");
}
return false;
}
And this is my form with its attributes in HTML:
<form name="myForm" onsubmit="return validateForm()" method="post" action="confirm.html" novalidate="novalidate" >
What happens is that when I click the Submit button after filling in all the requirements(so everything does not return false) , the form won't submit itself.
After reading around regarding return false, I tried adding else{ return true; } but all it does is submit my form without validation at all.
What do I do to make it work with only Javascript and/or HTML? Thank you!
At the end of the submission function, you are returning:
return false;
}
No matter if the validation was successful or not. This prevents the form from submitting. Make sure you are using return true here and correctly validate using a flag and then if the flag is true, return false.
You have already a flag isValid. Replace the above line with:
return isValid;
}
You need to check if your inputs have passed your tests.
You can do that by using your var isValid.
All you need to do is set isValid to false if one of your conditions was not met, and then return isValid.
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
isValid=false;
alert("Your name cannot be blank");
}
if (b == null || b == "") {
isValid=false;
alert("Enter a valid email address.");
}
if (c == null || c == "") {
isValid=false;
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
isValid=false;
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
isValid=false;
alert("Must select an Issue.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (g == null || g == "") {
isValid=false;
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
isValid=false;
alert("Preferred time must follow the format set.");
}
return isValid;
}

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.
Here's the phone number with dashes form that is working:
//Validates phone number with dashes.
function isTwelveAndDashes(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
and this is the one I can't manage to work out.
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') {
pass = false;
}
}
if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
You can do it very easily with regex:
return !!phone.match(/\(\d{3}\)\d{7}/g)
Live DEMO
Update:
The code you had didn't work because you forgot the else if:
else if (i == 4) { // Added the "else" on the left.
Checking phone number with RegEx is certainly the way to go. Here is the validation
function that ignores spaces, parentheses and dashes:
check_phone(num) {
return num.replace(/[\s\-\(\)]/g,'').match(/^\+?\d{6,10}$/) != null}
You can vary the number of digits to accept with the range in the second regular expression {6,10}. Leading + is allowed.
Something like that (a RegExp rule) can make sure it matches either rule.
var numbers = ['(1234567890','(123)4567890','123-456-7890','1234567890','12345678901'];
var rule = /^(\(\d{3}\)\d{7}|\d{3}-\d{3}-\d{4}|\d{10})$/;
for (var i = 0; i < numbers.length; i++) {
var passed = rule.test(numbers[i].replace(/\s/g,''));
console.log(numbers[i] + '\t-->\t' + (passed ? 'passed' : 'failed'));
}
EDIT:
function isDigit(num) {
return !isNaN(parseInt(num))
}
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') return false;
} else if (i == 4) {
if (c != ')') return false;
} else if (!isDigit(c)) return false;
}
return true;
}
// or...
function isTwelveAndPara(phone) {
if (phone.length != 12 || phone.charAt(0) != '(' || phone.charAt(4) != ')') return false;
for (var i = 1; i < phone.length, i != 4; i++) {
if (!isDigit(phone.charAt(i))) return false;
}
return true;
}

Categories

Resources