Validating more that one email field - javascript

Im using Joren Rapini's validation code to for my online form. Joren's Website
It allows you to check to see if an email address has been correctly entered, but I have 2 email addresses that I want to validate in the form.
Any idea how I would do this?
I've tried adding in email = $("#youremail"); as well as the one that's currently in the code which is email = $("#receiveremail"); but it only works for one.
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["youremail", "name", "receiveremail", "message"];
// If using an ID other than #email or #error then replace it here
email = $("#receiveremail");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field";
emailerror = "Not a vaild email";
});

He doesn't do a great job of explaining this, but it's fairly straightforward. You have to validate two separate email fields:
if (!/^S+#S+.S+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
var email2 = $("#youremail");
if (!/^S+#S+.S+$/.test(email2.val()) {
Of course it would be better to loop over the emails in a similar setup to how required is done.
Use var too.

You need to run the validation code for your other field
in document.ready
otheremail = $("#otheremail");
in form submit
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(otheremail .val())) {
otheremail .addClass("needsfilled");
otheremail .val(emailerror);
}
No offense to Joren Rapini but this code is hacky and shouldn't be used for other than the smallest purpose.

Related

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)!

Adding onto browsers' built-in form validation

I'm creating an email form for our website. I built the form using HTML5 and CSS to take advantage of browsers' built-in validation (using this shim to avoid compatibility problems). Now I want to add a "confirm your email address" field, which shouldn't be marked valid unless it matches the "enter your email address" field.
I've written some JavaScript to compare the two fields. Is there a way for JavaScript to mark a field as valid/invalid for the browser's built-in validation? Or do I need to switch to a third-party validation plugin to get this feature?
Found the answer right after I posted the question. You call <element>.setCustomValidity() on the field, passing in an empty string to set the field as valid. If it's not valid, you instead pass in a string with the reason why.
Here's my code:
$('#emailConfirmation').on('keyup', function() {
if ($('#emailConfirmation').val() == $('#email').val()) {
$("#emailConfirmation")[0].setCustomValidity("");
} else {
$("#emailConfirmation")[0].setCustomValidity("Check that you've typed your email address the same way in both places.");
}
});
Here it is again without jQuery:
document.getElementById('emailConfirmation').onchange = function() {
if (document.getElementById("emailConfirmation").value == document.getElementById("email").value) {
document.getElementById("emailConfirmation").setCustomValidity("");
} else {
document.getElementById("emailConfirmation").setCustomValidity("Check that you've typed your email address the same way in both places.");
}
}

Javascript not working after filename change

I created a simple registration (sign-up) form for my website.
The form includes a few validity checks (such as : making sure that the email is in the correct format; making sure that the username does not already exist in the database; etc, etc)
All these required JS, which I provided with the proper JS functions, and included a JS script with my files :
**<script src="jquery-1.11.2.js" type="text/javascript"></script>**
Everything was working perfectly..........until I changed the name of my registration file from "index.html" to "signup.php"
Now, it's all screwed up. The form still works. But, the JS functions and validity checks are dead! Nothing works.
There are no similar issues here on StackOverflow; however, I was able to find one issue on google. The poster suggested using a "Javascript Initialization" to solve the issue, but he did not provide an example of exactly how he did this.
Here is my JS code :
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 4;
//result texts
var characters_error = 'You must enter a minimum of 4 characters!';
var checking_html = 'Checking Username Availability....';
//when button is clicked
$('#login').keyup(function(){
//run the character number check
if($('#login').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
$('#email').keyup(function(){
//run the character number check
if($('#email').val().length > 0 ) {
//if it's bellow the minimum show characters_error text '
$('#email_availability_result').html(checking_email);
}
else{
//else show the cheking_text and run the function to check
$('#email_availability_result').html(checking_email);
check_email();
}
});
});
//function to check username AND email availability
function check_availability(){
//get the username
var login = $('#login').val();
var button_check=true;
//use ajax to run the check
$.post("check.php", { login: login },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
button_check=false;
document.getElementById("submit").disabled = false;
$('#username_availability_result').html(login + ' is
available.');
}else{
//show that the username is NOT available
button_check=true;
document.getElementById("submit").disabled = true;
$('#username_availability_result').html('Sorry, but [' + login +
'] is not available. Please choose another username.');
}
});
}
This script checks for "username availability" and also that the username has "a minimum of 4 characters" and also "email availability", etc, etc
(I did not enter the full code, as I assume it is not necessary). These are just examples of part of my code.
And here is the form (the input entry for username)
Choose a username :
UPDATE
I solved the issue of why the JS functions were not working : I had to specify the FULL PATH to the JS source-file, beginning with https://......etc.
However, something still remains unclear : the form displays the message "Checking Username Availability".........or "Checking Email Validity". But, if the username is available/unavailable, or email is valid/invalid.........it does not display these messages!
The "Checking Username Availability" message remains stuck on display :((
Answer found.
A simple, stupid mistake on my part (haha)
After changing the file name to "sign-up.php", I forgot to remove the PHP extension. So, naturally, my server did not know where to look for it

Javascript driven forms in Django

Django uses his forms API for input validation. The form is sent to the template, and it is rendered as an html (as_p and friends).
When the user is ready, he POST the form, the data is validated, and the form is re-rendered on the template if it is not valid.
This is odd when the form is not valid just because lack of enough caracteres (i.e. min_length) on a field or invalid characters: one POST too much just to tell the user it is missing something very basic.
So, is there any available way (Django or app) of rendering a form with javascript code that "tests"[*] some of the form' fields on the client-side? I.e. have a form which is rendered as_javascript(...) that dynamically shows error messages that would be shown by form.errors?
This should not work for all fields because some require a database hit, but it should work on simple (and most common) fields, namely CharField, TextField, etc.
[*] "tests" because validation has always to be made also on the server-side.
So you want to validate something in JS before submitting. Here's one way to do that.
Instead of putting an input of type submit in the form you should put a button of type button:
<form id="my-form" submit="...">
...
<input type='button' id='submit-button' value="Save">
</form>
Note that unless you specify the type as "button", it will still try to submit.
Then in a JS file you write something like this (include jQuery in your HTML file):
$('#submit-button').click(function() {
var errors = testErrors(); // this function tests for the errors.
if (errors != "") {
alert(errors);
} else {
$('#my-form').submit();
}
}
Example testErrors():
function testErrors() {
var country = $("#id_country").val();
var city = $("#id_city").val();
var errors = "";
if (country == "") {
errors += "- Please select a country\n";
}
if (city.length <= 10 ) {
errors += "- Your city name is too short\n";
}
return errors;
}
So in testErrors you define your own tests for each field. In this example there are two, country and city. For country the code tests whether it's blank and for city whether it's longer than 10 characters. You can define further tests of your own. Please refer to jQuery documentation as well on how to retrieve values from different types of form fields.

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