I have 4 js function:validateDate,validateRoom,validateCardDate and validateCard
now on submit of form I want to execute all of them.OR I want to execute 2nd if 1st is true such for all. I have implement some advise like:
return fun1() && fun2() && fun3(),
return fun1(); fun2(),
and made wrapper function too.. but could not get success.
UPDATE:MY CODE IS:
is their any mistake in code? every attempt has been failed so far.
function validateDate() {
var x = document.forms["form"]["checkin"].value;
var y = document.forms["form"]["checkout"].value;
if (x == y) {
alert("checkout date should be different from checkin");
return false;
}else if(x > y){
alert("checkout date should be greater");
return false;
}else{return true;}
}
function validateRoom() {
var a = document.forms["form"]["singleroom"].value;
var b = document.forms["form"]["doubleroom"].value;
var c = document.forms["form"]["tripleroom"].value;
if (a == 0 && b==0 && c==0) {
alert("Please select atleast one field");
return false;
}else{return true;}
}
function validateCardDate() {
var month = document.forms["form"]["month"].value;
var year = document.forms["form"]["year"].value;
var today = new Date();
if(year < today.getFullYear()){
alert("Card is expired");
return false;
}else if(year == today.getFullYear()){
if(month <= today.getMonth())
alert("Card is expired");
return false;
} else {return true;}
}
function validateCard() {
var cardType = document.forms["card"]["cardType"].value;
var cardNumber = document.forms["card"]["cardNumber"].value;
if(cardType == "visa"){
var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid Visa credit card number!");
return false;
}
}else if(cardType == "americanexpress"){
var cardno = /^(?:3[47][0-9]{13})$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid Amercican Express credit card number!");
return false;
}
}else if(cardType == "mastercard"){
var cardno = /^(?:5[1-5][0-9]{14})$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid mastercard credit card number!");
return false;
}
}
else if(cardType == "jcb"){
var cardno = /^(?:(?:2131|1800|35\d{3})\d{11})$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid JCB credit card number!");
return false;
}
}
}
Simply do:
function main(){
//functions to exexute.
}
Then do:
onsubmit="main()"
If you want to execute the second if the first is true then
The first function must return true
if(main()){if(//otherfunction){}}
Try this:
if (func1()){
if(func2()){
if(func3()){
return func4()
}else{
return false;
}
}else{
return false
}
}else{
return false
}
Every functions func1...func4 should be return a false or true value.
Create a new function which has all those four functions inside it
Example:
function ParentFunction() {
validateDate()
validateRoom()
validateCardDate()
validateCard()
}
An onSubmit call the ParentFunction(). This way you can even use arguments and decision controls to run those functions in any sequence you like.
UPDATE
Try this:
var validateDate = function () {
// Statements
return true // if conditions are what you want
}
var validateRoom = function () {
// Statements
return true // if conditions are what you want
}
var validateCardDate = function () {
// Statements
return true // if conditions are what you want
}
var validateCard = function () {
// Statements
return true // if conditions are what you want
}
function ParentFunction() {
if (validateDate() == true) {
if (validateRoom() == true) {
if (validateCardDate() == true) {
if (validateCard() == true) {
return true
}
}
}
}
return false
}
Hope it helps!
Related
I am trying to validate a form in my project with native JS
I am creating a function for every input validation
I created the first function to validate the user No. and it worked well
but when I created the user name validation function and tested it it shows the user No. error two times, and I tried to enter the No. and not enter the name and no errors displayed
Can anyone help me please?
this my code
$('#addUserBtn').click(function (e) {
e.preventDefault();
let valid = false;
let errors = [];
if (validateNo($('#userNoInput').val()) == true) {
return true;
} else {
errors.push(validateNo($('#userNoInput').val()));
console.log(errors);
}
if (validateName($('#userNameInput').val()) == true) {
return true;
} else {
errors.push(validateName($('#userNameInput').val()));
console.log(errors);
}
if (errors.length == 0) {
valid = true;
}
if (valid == true) {
let user = {
no: $('#userNoInput').val(),
name: $('#userNameInput').val(),
email: $('#userEmailInput').val(),
tel: $('#userTelInput').val(),
dob: $('#userDobInput').val(),
rmk: $('#userRmkInput').val(),
}
usersContainer.push(user);
localStorage.setItem('myUsers', JSON.stringify(usersContainer));
displayUsers();
//clearForm();
} else {
let messages = Object.values(errors);
let errorsMarkup = ""
for (let i = 0; i < messages.length; i++) {
errorsMarkup += `${messages[i]}`;
}
console.log(errorsMarkup);
errorsMarkup = errorsMarkup.replace(/\./g, '<br>');
Swal.fire({
icon: 'error',
title: 'خطأ...',
confirmButtonText: 'حسناً',
html: errorsMarkup
});
}
});
function validateNo(input) {
if (input == '') {
let error = "You must enter User No.";
return error;
}
let reg = /^\d+$/;
if (reg.test(input) == false) {
let error = "Not valid User No.";
return error;
}
return true;
}
function validateName(input) {
if (input == '') {
let error = "You must enter User Name.";
return error;
}
let reg = /^[a-z\s]{0,255}$/i;
if (reg.test(input) == false) {
let error = "Not valid User Name.";
return error;
}
return true;
}
In your validation of the name field, you're calling validateNo instead of validateName in the else.
if (validateName($('#userNameInput').val()) == true) {
return true;
} else {
errors.push(validateNo($('#userNameInput').val()));
console.log(errors);
};
Additionally, you're returning from your function early. This means that if there is no validation error for validateNo it will return true and not validateName.
if (validateNo($('#userNoInput').val()) == true) {
return true;
} else {
errors.push(validateNo($('#userNoInput').val()));
console.log(errors);
}
if (validateNo($('#userNoInput').val()) == true) {
return true;
} else {
errors.push(validateNo($('#userNoInput').val()));
console.log(errors);
}
if (validateName($('#userNameInput').val()) == true) {
return true;
} else {
errors.push(validateName($('#userNameInput').val()));
console.log(errors);
}
I would suggest changing your code to something like:
if (validateNo($('#userNoInput').val()) == true) {
errors.push(validateNo($('#userNoInput').val()));
console.log(errors);
}
if (validateName($('#userNameInput').val()) == true) {
errors.push(validateName($('#userNameInput').val()));
console.log(errors);
}
You are ending your function if the userNoInput input is validated because of the return true in the if block.
if (validateNo($('#userNoInput').val()) == true) {
return true; // This ends the function early, you want the function to keep going to validate the other fields
} else {
errors.push(validateNo($('#userNoInput').val()));
console.log(errors);
}
You need to remove the return true, just check if the individual validation functions return false, and keep going until all checks are done.
Then after the individual validations, check if the errors array is empty. If it is empty, it means there are no errors.
This code return "false" for test input "1" only when I submit in leet code. It's working when I do it in my local or leet code editor for the same input
var temp = 0;
var rev = 0;
var palindromeCheck = function (org) {
temp = org % 10;
rev = rev * 10 + temp;
org = parseInt(org / 10);
if (org > 0) {
palindromeCheck(org);
}
return rev;
};
var isPalindrome = function (x) {
if (x == 0) {
return true;
}
else if(x > 0) {
var value = palindromeCheck(x);
if (value === x) {
return true;
}
else {
return false;
}
}
else {
return false;
}
};
your palindromeCheck() function return a number. The problem comes from this part, where you strictly compare a number and a string:
if (value === x) {
return true;
}
else {
return false;
}
try to do :
if (value == x) {
return true;
}
else {
return false;
}
or
return (value == x);
else you can just use parseInt() function.
I am stuck here with some issue. There are 3 two entry boxes: for birthday, an amount and an interest rate (%). If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
So the issue is: When I enter an incorrect date, I get a notification. However, the interest is still calculated afterwards. I want to prevent code from being executed with incorrect input.
document.getElementById("button").onclick = loop;
var inputA = document.getElementById("inputA");
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function allFunctions() {
correctBirthday()
sum();
rate();
loop();
}
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
if (inputA.value == '')
{ alert('Please enter a value for input A');
return;
}
}
function correctDate(datum) {
var vorm = /^\d{2}-\d{2}-\d{4}$/;
return vorm.test(datum);
}
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
alert("The form of the date is incorrect");
return;
}
if ( validDate(d) ) {
result.innerHTML = '';
}
}
function rate() {
var r = rentepercentage.value;
if ( correctRate(r) == true ) {
alert("The form of the amount entered is incorrect");
return;
} else {
result.innerHTML = '';
}
}
function correctRate(rente) {
var vorm = /[a-zA-Z]/;
return vorm.test(rente);
}
function sum() {
var s = bedrad.value;
if ( correctSum(s) === true ) {
alert("The form of the amount entered is incorrect");
return;
} else {
result.innerHTML = '';
}
}
function correctSum(som) {
var vorm = /[a-zA-Z]/;
return vorm.test(som);
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputA" value="05-06-1986"><br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
So the issue is: When I enter an incorrect date, I get a notification. However, the interest is still calculated afterwards. I want to prevent code from being executed with incorrect input.
In your allFunctions function:
function allFunctions() {
correctBirthday()
sum();
rate();
loop();
}
If correctBirthday returns undefined, allFunctions does not know that it should stop. You have two main options:
Throw an error if the birthday is incorrect, and catch it later:
function allFunctions() {
try {
correctBirthday()
sum();
rate();
loop();
} catch ( error ) {
alert( error.message );
}
}
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
throw new Error("The form of the date is incorrect");
}
if ( validDate(d) ) {
result.innerHTML = '';
}
}
Let correctBirthday return true or false depending on whether it succeeded, and let allFunctions respond appropriately:
function allFunctions() {
let birthdayIsCorrect = correctBirthday();
if ( !birthdayIsCorrect ) {
return;
)
sum();
rate();
loop();
}
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
alert("The form of the date is incorrect");
return false;
}
if ( validDate(d) ) {
result.innerHTML = '';
}
return true;
}
EDIT: If you want this behaviour when validDate(d) is false as well, try...
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
throw new Error("The form of the date is incorrect");
}
if ( !validDate(d) ) {
throw new Error("The date is invalid");
}
result.innerHTML = '';
}
// or...
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
alert("The form of the date is incorrect");
return false;
}
if ( !validDate(d) ) {
alert("The date is invalid");
return false;
}
result.innerHTML = '';
return true;
}
im am a newbie to javascript, i write a code to add a validation to my form, this is my script:
function validateForm()
{
var name=document.forms["form"]["entry.1017659850"].value;
var email=document.forms["form"]["entry.808043133"].value;
var check=document.forms["form"]["entry.317648050"].checked;
if(name == ""){
document.getElementById("alertname").style.display="block";
return false;
}
if(email == ""){
document.getElementById("alertemail").style.display="block";
return false;
}
if(!check){
document.getElementById("alertcheck").style.display="block";
return false;
}
return true;
}
And i want to add my email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
The question is how will i do it, i am not familiar with the functions on javascript.
Thank you.
.test() returns a boolean. If it doesn't match the given regex, it will return false, so you can use its return value to know if it validates or not:
if(email == "" || !validateEmail(email)){
document.getElementById("alertemail").style.display="block";
return false;
}
You can validate your email like this. I got this from here.
function validateEmail(email) {
const pattern = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return pattern.test(String(email).toLowerCase());
}
var email = "-9i{#ssss.ss";
var is_valid = validateEmail(email);
if(is_valid === true){
console.log("Yes Valid Email")
}else{
console.log("Not Valid Email")
}
Try this:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateForm()
{
var name=document.forms["form"]["entry.1017659850"].value;
var email=document.forms["form"]["entry.808043133"].value;
var check=document.forms["form"]["entry.317648050"].checked;
if(name == ""){
document.getElementById("alertname").style.display="block";
return false;
}
if(email == ""){
document.getElementById("alertemail").style.display="block";
return false;
}
if(!check){
document.getElementById("alertcheck").style.display="block";
return false;
}
if(!validateEmail(email)){
document.getElementById("alertemail").style.display="block";
return false;
}
return true;
}
var email = "abc#abc.com";
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email))
{
alert("invalid");
}
else
{
alert("valid");
}
So the validation for the form works, but I cannot get it to send to the php file. I'm assuming it has something to do with the return false/true and the end.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '')
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
if (email == '')
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
if (msg == '')
{
$('.msgerror').html('What can we help you with?').fadeIn(1000);
}
return false;
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
I think your last section of code should read like this:
if($.trim($('.nameerror').text()) == '')
{
// You can do stuff here first if everything is good.
return true;
}
else
{
// Or you can do stuff here for a failed submission.
return false;
}
You are exiting the function before the last if statement is checked.
You must use this code:
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '') {
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
return false;
}
if (email == '') {
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
return false;
}
if (msg == '') {
$('.msgerror').html('What can we help you with?').fadeIn(1000);
return false;
}
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
Instead of checking to see if a particular element has html in it... why don't you just set a flag? This makes everything a bit more simplistic.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
var flag = true;
//do this for each of your if statements
if(there is an error case) {
//do whatever you want to the DOM
flag = false;
}
return flag;
}