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.
Related
I need help with returning a boolean value from my validateItems() function. And my addPatrons() function (which calls the validateItems() function) must receive the boolean value returned by validateItems() and store it in a variable named "isValid". Then i need to Check the value of isValid if it is true, then use $('myform').submit(); but if it is false, then display "Patron Not Added!" in the endmessage.
this is what i have so far, its not finished because i am lost. its probably something simple but i am not getting it.
var validateItems = function () {
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if (firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
}
var lastName = $("lastname").value;
if (lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
}
var addpatron = function (validateItems) {
var isValid =
if () {
$("myform").submit();
}
else
if () {
$("endmessage").innerHTML = "Patron Not Added!"
}
}
var validateItems = function() {
var formValid = true
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if(firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
formValid = false
}
var lastName = $("lastname").value;
if(lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
formValid = false
}
return formValid
}
var addpatron = function(validateItems) {
var isValid = validateItems ()
if (isValid ){
$("myform").submit();
}
else if (){
$("endmessage").innerHTML = "Patron Not Added!"
}
}
You have to change your form element as below
<form onsubmit="return validateAndSubmit();" >...</form>
And use the validate function as below
validateAndSubmit(){
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(invalid) return false; // prevents the form from submitting
else return true; // submits the form
}
EDIT 1
if you don't have to submit the form literally, but only perform an operation on submit you can return false always.
validateAndSubmit(){
event.preventDefault();
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(!invalid){
addPatron(); // perform add operation only when form is valid
}
return false;
}
I have made the following changes.
returning false always.
If not invalid calling the addPatron() function
Added event.preventDefault() for additional event bubbling to stop.
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!
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;
}
when i run this program the validatePhone();, validateAddress(); and validateCity(); are completely skipped, why? heres my JS:
function validatePage()
{
var valid = false;//sets valid.
var msg = "";//sets message to blank.
validateFname();
function validateFname()
{
var fnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(firstName.value.match(fnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateLname();
}
function validateLname()
{
var lnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(lastName.value.match(lnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePhone();
}
function validatePhone()
{
var nameTxt = /^[0-9]+$///sets valid inputs for recipient name.
if(Phone.value.match(nameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateAddress();
}
function validateAddress()
{
var addressTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(address1.value.match(addressTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateCity();
}
function validateCity()
{
var cityTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(cityTown.value.match(cityTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePostcode();
}
function validatePostcode()
{
var postcodeTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(postcode.value.match(postcodeTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
}
if(valid == true)
{
window.open("checkout_step_5.html");
}
else
{
msg="Not all required fields were filled."
alert(msg);
return false;
}
}
i checked for spelling mistakes and there is none well none that i have noticed i really dont know why this isnt working?
Try putting entire code in try catch as of now I did not get any exception
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validatePage()
{
try{
var valid = false;//sets valid.
var msg = "";//sets message to blank.
validateFname();
function validateFname()
{
var fnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(firstName.value.match(fnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateLname();
}
function validateLname()
{
var lnameTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(lastName.value.match(lnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePhone();
}
function validatePhone()
{
var nameTxt = /^[0-9]+$///sets valid inputs for recipient name.
if(Phone.value.match(nameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateAddress();
}
function validateAddress()
{
var addressTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(address1.value.match(addressTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validateCity();
}
function validateCity()
{
var cityTxt = /^[a-zA-Z]+$///sets valid inputs for recipient name.
if(cityTown.value.match(cityTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
validatePostcode();
}
function validatePostcode()
{
var postcodeTxt = /^[0-9a-zA-Z]+$///sets valid inputs for recipient name.
if(postcode.value.match(postcodeTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
}
}
if(valid == true)
{
window.open("checkout_step_5.html");
}
else
{
msg="Not all required fields were filled."
alert(msg);
return false;
}
}catch(e){
alert(e);
}
}
</script>
</head>
<body onload="validatePage()">
</body>
</html>
And another suggestion if Valid becomes false once please break through the function using return. No Point in checking always if one parameter is false.
if(firstName.value.match(fnameTxt))//checks if there has been an entered value, then sets valid to true.
{
valid = true;
}
else
{
valid = false;
return;
}