Adding onto browsers' built-in form validation - javascript

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.");
}
}

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

Clear validation error messages after errors have been corrected

I have a custom validator in asp.net that validates address client side, which works perfectly. Except, when i correct the error by filling up the text box, the error message doesn't disappear like it does for required field validators. The reason i use a custom validation is because i have separate boxes for street name, number, suburb etc and want to validate all of them at once.
Here is my JS:-
function ValidateAddress(src, args) {
var unit = document.getElementById('TextUnit');
var street = document.getElementById('TextStreet');
var sub = document.getElementById('TextSuburb');
var pc = document.getElementById('TextPC');
if (unit.value == "" || street.value == "" || sub.value == "" || pc.value == "")
{ args.IsValid = false; }
else { args.IsValid = true;}
}
Is there a way of making the error message disappear without using jquery? I solely have to use JS or HTML
It looks like your ValidateAddress function is called from somewhere else - probably a hook your validation framework has put on the form submit action or something similar. If your validation framework is handling re-validation of most of your controls after they have changed, it must be hooking the onchange event for those controls somehow. You will need to investigate how your validation framework is finding the controls it needs to watch for changes and update your address controls so that your validation framework detects and monitors them. Once your validation framework is handling onchange events for your address input controls the validation will be re-run and the error cleared when the user enters enough information.
Without more details about what validation framework you're using - or if you're using a homegrown validation framework, as seems likely - it'll be hard to give you a more specific answer.

I just want my form to be key with a specific answer by my customer , how to?

I do not want to used captacha on my site. as such i would just like my customer to key a specific answer in the form that i have created.
For example = What is 3 + 4 ? and i only want the field to be key with number 7. for instance if my customer keyed any other number then 7, the form would not be submitted and would request for the right answer.
I'm trying to use spry widget to perform this trick but have failed multiple times even after changing the html code.
here's the code:
<span id="sprytextfield4">
<input type="text" name="huamn" id="huamn" />
<span class="textfieldRequiredMsg">
Please provide an answer
</span>
</span>
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "text", {minValue:7, maxValue:7, maxChars:1});
if you want to validate using javascript on the client, here's a quick and dirty way that I've used.
note: you still need to validate the same question on the server to ensure the spammer hasn't circumvented by disabling Javascript
jQuery
$('#submit').click(function (event) {
var color = $('#color').val().toLowerCase();
if (color != 'orange') {
alert('incorrect');
} else {
alert('yay!');
// submit the form
// BUT DON'T FORGET TO VALIDATE input.color AGAIN ON THE SERVER.
}
});
http://jsfiddle.net/g4Gu8/1/
if your site is of low importance to spammers... IE: not StackOverflow or Redit, you can typically get away with this type of validation and pretty much avoid getting spam. If your site becomes a direct target for attack, and bots are written to circumvent this very low level of protection, you should look into using one of the many pre-build captcha libraries out there and implement both the server side and client side validation. I for one can't stand image CAPTCHA's, so I prefer a method of "human verification" that is less intrusive.

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.

Validating more that one email field

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.

Categories

Resources