I'm trying to stop people from sending me blank emails through my contact us on my website. On my main website I have succeeded with the following javascript:
<script type="text/javascript">
function checkForm(f)
{
if (f.elements['cf_name'].value == "" && f.elements['cf_email'].value == "" && f.elements['cf_message'].value == "")
{
alert("You have not filled in all of the required fields.");
return false;
}
else
{
f.submit();
return false;
}
}
</script>
Although this works, when I implemented the same on my mobile website, people are still able to send blank emails.
The HTML code I used for the form check is:
<form action="contact.php" method="post" name="sform" onSubmit="return checkForm(this);">
So my question is how do i stop form submission if the fields are empty, on a mobile device (specifically iPhone)
Are you sure this isn't a logic error? Seems like this:
if (f.elements['cf_name'].value == "" && f.elements['cf_email'].value == "" && f.elements['cf_message'].value == "")
Should be:
if (f.elements['cf_name'].value == "" || f.elements['cf_email'].value == "" || f.elements['cf_message'].value == "")
Although client-side validation is useful because it's more immediate, you should never rely on it, and using Javascript alone to do this sort of check is riddled with holes (as you found). Write code which will work nicely if Javascript works, and will still do the validation you want if Javascript is not implemented.
Since you are sending your form data to a php script, do your checking there as well as in the client and only send the mail if the form data is valid.
Related
Javascript isn't really my strong point. I already have the php working for the captcha on the backend but i want to be able to validate the form with JS to prevent the user from sending a form when the captcha hasn't been completed.
This is the example the hcaptca site gives:
https://medium.com/#hCaptcha/using-hcaptcha-with-php-fc31884aa9ea
And here is the JS code they give as an example.
$("form").submit(function(event) {
var hcaptchaVal = $('[name=h-captcha-response]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
I'm not 100% sure but that appears to be Jquery and my site does not use Jquery. so i need a vanilla JS solution.
Let me try to explain:
$("form").submit(function(event) { }
// When the form is submitted
var hcaptchaVal = $('[name=h-captcha-response]').value;
// Retrieve the value of the captcha (= the value of an HTML element with the tag name="h-captcha-response"
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the Captcha");
}
// If the value of the captcha is empty, stop the form submission and alert the user
So if you are searching for a Vanilla JS solution, it's not that hard, all you have to do is convert the jQuery parts :
document.querySelector("#yourFormId").addEventListener("submit", function(event) {
var hcaptchaVal = document.querySelector('[name="h-captcha-response"]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
I have already built a form validator in JS, a portion of which is displayed below. I just need help in displaying an error and scrolling to the field.
Okay, so each <input> will have attributes specifying the validation they need, eg:
<input data-mandatory="yes" data-validation="phone" data-max-digits="10">
There attributes are parsed at the time of form submission, and if I come across an errornous field I need to scroll to that field and display an error in English (multilingual not needed).
var $form = $('#main-form');
$form.submit(function(event) {
event.preventDefault();
// per field
$form.find("input,textarea").each(function(f, field){
// read metadata
var type = $(field).attr("type");
var mandatory = $(field).data("mandatory");
var maxDigits = $(field).data("max-digits")) || 1000;
var validation = $(field).data("validation");
// read value
var value = $(field).value();
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
// HOW DO I SHOW AN ERROR AT THE CURRENT FIELD?
// and how do I scroll to it?
}
}
});
});
Edit: I've got a non-trivial amount of code in node.js (5K LOC) which I'm porting to the client side, which is required by my organization. That code is not displayed above.
Edit: I've looked online for an hour but the jQuery form validator libraries that I've seen do not function the way I need. I already have form sanitation & validation code (which supports various data types like phone number, ZIP code, etc) in Node.js which I'm just porting to the client side.
First of all i would recommend to use some free validation plugin. But, if you want for some reason to write it your self, than the answer to your question is:
First you need to have the error message hidden somewhere in your markup. There is a number of ways to do this. Most common solution would be something like that:
<div>
<input type="text" required />
<p class="error">Error</p>
</div>
Than you need to display it, in your example it could be done like this:
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
//show error
$(this).parent().find('.error').show();
//scroll
$('html, body').animate({
scrollTop: $(this).offset().top
}, 2000);
return; // stop validation(becouse you dont want to scroll more times)
}
}
You will need to figure out some more things (like hide all the errors before validating again), but this should answer your question.
What is the best practice in checking a user has actually completed the captcha before form submission?
From the documentation I can see there is 2 callback functions data-callback and data-expired-callback.
The plan is to manipulate a boolean javascript variable setting to true/false on successful completion or on expiration and then check that the variable is true before form submission.
From a user perspective this will ensure that the user fills out the captcha before submission.
Malicious users could overwrite the javascript variable but the server side captcha validation will protect against this.
First in your form you have to put onsubmit="return check()". That means when you're submiting the form, before sending datas it will execute the function named check(). If the function returns false the form won't submit. It will look like this :
<form action="page.php" method="POST" name="form" onsubmit="return checkCaptcha ()">
Then you have your function :
<script language="javascript">
function checkCaptcha ()
{
var captcha = document.getElementById('captcha ').value;
if (captcha == "" || captcha == " ")
{
alert("please fill the captcha ");
return false;
}
else
if (captcha .length != 7)
{
return false
} // and so on
else
{
// if everything is ok you can submit
return true;
}
}
</script>
So I have a "create an account" form with an age input. I have the age requirement set to 16. What I want to do is if the person is under the age of 16 it gives an alert message, and then when the user clicks the OK button on the alert window it sends them back to the index page.
Here is what I have for JS code:
if (age == null || age == "")
{
alert("Please enter your age to continue.");
return false;
}
else if (age == isNaN(age))
{
alert("Age input was not a number!\nPlease enter your age to continue.");
return false;
}
else if (age < 16)
{
alert("You are not old enough to have an account.\n If you have concerns or questions about our age policy please send them to ghost565xster#gmail.com.");
return false;
}
Basically when it runs that last "else if" statement and finds the input was less than 16, I want it to redirect the user to the index.html (Home) page after displaying the alert message.
I have tried using:
else if (age < 16)
{
alert("You are not old enough to have an account.\n If you have concerns or questions about our age policy please send them to ghost565xster#gmail.com.");
location.assign("index.html");
return false;
}
I have also tried location.href but neither work. Any help on this will be greatly appreciated!
Just assign a new value to the location property. location = "index.html"
this What's the difference between window.location= and window.location.replace()?
Best practice since you dont want them pressing back and getting in to a loop would be to use window.location.replace("sorryYouAreJustTooYoung.html");
Use this:
window.location.href = "your location";
You should post your html content too as you may have a problem there. I had this problem some time ago, when the age was under the required age limit i was directed to a site i never specified with the window.location.href.... even though it was assigned to a different site, the problem may be that you have wrapped an anchor tag around it so it will direct you to the site that you specified on your html page, i suggest you check that you dont have an anchor tab directing you elsewhere on your html page!
easiest as possible:
window.location = "http://www.google.com/"
Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.