Question about web forms, JavaScript validation function unreachable - javascript

Good day,
I've been working on this for class. I submitted the assignment and got a good grade - the professor didn't even lower my grade because I wasn't able to get this working, but I'm still frustrated because what I want this to do is to take a look at the Help Request form, alert me that it's checked, and to validate the email address. But the function seems to be unreachable.
I've made this fiddle here:
https://jsfiddle.net/b7j3ekts/
Stack overflow requires that I post code as well, but the fiddle is better I think:
/* This function never fired. I spent alot of time with it and I'm really frustrated and even though I posted my problem online and am going back and forth with
it, I kinda ran out of time to fix it. I was trying to do the part of the assignment where we looked to see if email was checked and then validated the email address. */
if (document.getElementById("contactemailH").checked === true) {
alert("Checked!");
/* Checks the email field to make sure that it's an email address in formHELP */
var emailaddy2 = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (document.forms["formHELP"]["FromAddress"].value.match(emailaddy2)) {
}
else {
alert("Please input a valid email address.");
return false;
}
}
}
The offending code starts at around line 123 of the js file.
Any advice appreciated. :)
-- Mark

if (document.getElementById("contactphoneH").checked === true ||document.getElementById("contactemailH").checked === true ) {
alert("Checked!");
/* Checks the email field to make sure that it's an email address in formHELP */
var emailaddy2 = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (document.forms["formHELP"]["FromAddressH"].value.match(emailaddy2)) {
}
else {
alert("Please input a valid email address.");
return false;
}
}
You just had misspelled tags.

You seem to need an event listener. The JavaScript loads once, does anything you've marked as immediate, and then it just sits there dormant. If you want a function to run you have to call it by name, or tell JavaScript to watch for an event.
In your case I'd tell JavaScript to wait for the event "blur", which is when an element was focused and then loses focus, so it's great for form fields.
document.getElementById('contactemailH').addEventListener('blur', function(event) {
validateEmail(event.target.value)
})
let validateEmail = function (emailaddy) {
// do your check here
}
Let me know if I'm off-base; I'm reading your fiddle on a mobile and jsfiddle is not mobile friendly at all.

Related

Update value of INPUT in externally loaded FORM not working

total programming novice here - I don't know much of javascript, wasn't programming since university (about 10 years ago) - trying to solve one specific problem on my website.
I am using CRM Bitrix24 and I have an unsubscribe form from this CRM placed on my website. I need to setup the form the way that the email is loaded from URL parameter.
I have done that simply by loading the input and set input.value = "email from URL". My problem is that the form has some kind of validation, and even though there is a text filled in the input field, the form is giving me the error: Field is required.
Screenshot here: https://ibb.co/Ns33GVN
The code of external form look like this:
<script data-b24-form="inline/120/8y7xg2" data-skip-moving="true">(function(w,d,u){var s=d.createElement('script');s.async=true;s.src=u+'?'+(Date.now()/180000|0);var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);})(window,document,'https://cdn.bitrix24.com/b7014957/crm/form/loader_120.js');</script>
My JS:
function emailPopup(){
var params = new window.URLSearchParams(window.location.search);
var email = params.get('email');
const emailCollection = document.getElementsByName("email");
for (let i = 0; i < emailCollection.length; i++) {
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
}
}
} window.addEventListener('load', function () {
emailPopup();
})
I tried to understand how the validation is done, but with no luck. The field has autocomplete = yes, so once it is submitted, next time it's not shooting the error, but the form is sent with the email submited at the first attempt, even though it is showing another one when hitting the SUBMIT button. It seems like it's only showing the email address from URL parameter, but in fact it's using wrong value, it's even empty (first attempt) or wrong (second attempt).
Is there a way how to force the field to pretend it was modified by user? Any ideas?
I have tried to setup similar environment here in jsfiddle: https://jsfiddle.net/e395wf6m/17/
Thanks a lot for any feedback!
I have a theory and it seems to be correct, as I tested it in your fiddle.
My theory is that the validation is done by firing a change event, so you need to trigger it. Luckily JavaScript let us do it:
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
// to trigger the change event
emailCollection[i].dispatchEvent((new Event('change')));
}
As I said, it worked when I tested it on your fiddle, let me know if it works for you =]

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

JQuery/Javascript: Error Message not displayed on Form

So basically I have a form where a user is allowed to create a group. An error message is supposed to be displayed if the user does something they are not supposed to for example they enter a group name that already exists. My code is shown below.
Any help would be appreciated.
Just a side note, any error message that is related to the field works fine. For example, if you don't enter anything into a required field, error message is displayed as it should on the form.
I'm not too familiar with that code that's creating the group form, but it seems that
%div{:id => "id___all__"}
may not be creating the field
$('#non_field_errors');
that you're trying to reference in
jQuery.each(errors, function(i, error) {
if (field != '__all__') {
$fieldId = $('#id_'+field);
} else {
$fieldId = $('#non_field_errors');
}
$fieldId.closest('.control-group').addClass('error');
$fieldId.parent().append(
$('<span class="error_span">').addClass('help-inline').append(error));
})
Basically, it SEEMS to me, without being 100% familiar with all this, that you're trying to place the errors into
$('#non_field_errors');
when you should be putting it into
$('#id___all__');
So nothing's happening. Let me know if this points you in the right direction. The loop itself appears to be working fine.

Check if correct e-mail was entered

I have a field for users to write their e-mail address in. It is optional, so I need to first check if something was entered in the field, if nothing was entered then do nothing, but if something was entered than check if it is an e-mail.
Right now I'm at this point
var email = $("input#sc_email").val();
if (email == "") {
// If e-mail field is empty do nothing
} else {
// If something was entered
// [CODE HERE] Check if valid e-mail was entered, if not show error message
$("label#email_error").show(); //error message
$("input#sc_email").focus(); //focus on email field
return false;
}
I'm not even sure if that is right, but I think it is. Right now I need help with gaps in code, I marked them as [CODE HERE]. Could anyone suggest a solution please.
You could use the jQuery validate plugin for this, but if you only want to check the validity of an email address in one field, that is a little bit of overkill.
Instead, the regular expression in the function below will make sure the format of the email address is correct, should a value have been entered.
var email = $("input#sc_email").val();
if (email !== "") { // If something was entered
if (!isValidEmailAddress(email)) {
$("label#email_error").show(); //error message
$("input#sc_email").focus(); //focus on email field
return false;
}
}
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
You could use regular expressions to validate the email address in JavaScript.
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);
}
This will, however, only validate that it is a valid email address formatted string. flibble#flobble.com would be valid, even if no-one actually has that email address.
Have a look at this question.
I would recommend validation both at client side and at server side, you could simply use this code:
alert(/\S+#\S+\.\S+/.test('asdasd#asdasd#asdd.com'));
alert(/\S+#\S+\.\S+/.test('asdasd234#asdd.com'));
but importantly, use server side validation and methodology, like sending click-link-mail, to verify your client email address or mailing random number etc.

Categories

Resources