I am working with a form that has a catcha image. When a user fills out the form, and presses submit ( and only when the captcha number is wrong) the fields are reset or cleared. How can I prevent this from happening?
If a visitor fills out the form, presses submit, the expected behaviour is theform is submitted, or if the captch number is wrong, retain the information that the visitor had input in the fields and ask the visitor to fill in the correct captcha number...
Here is the js:
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 == '');
} }
When you want to prevent the default behaviour you've to use a callback function like this:
function onsubmit_handler(evt) {
if (/* validation is ok */) {
return true;
}
else { /* validation is not ok */
evt.preventDefault();
return false;
}
}
yourfom.onsubmit = onsubmit_handler;
Am I correct in believing that the captcha is validated (only) on the server after a successful validation by the JS (i.e., not via an Ajax call in the form submission event handler)? Am I further correct in believing that you're doing a true HTML form submission instead of an Ajax form submission in the background?
If both of those are true, then the problem probably isn't in your JavaScript at all (I say "probably" only because you could conceivably have a JS function that clears all the form fields on load or something like that). You're submitting the form to the server, the server looks at the captcha, sees that the answer is wrong, and displays the form again -- with blank values. You need to change your server code to include the user's previous answers as value attributes (or selected options or whatever as appropriate for the element type) when it writes the form after a server-side validation failure.
Related
I'm getting the following error with the following JavaScript code:
RangeError: Maximum call stack size exceeded
I'm assuming that this means that I accidentally coded an infinite loop into my JavaScript. This code is from an ASP.NET MVC application that uses jQuery Validate. The purpose of this code is to check for images captured on the page prior to submission.
Essentially, this is another piece of front-end validation that needs to occur alongside jQuery Validate. It seems as though my only option is to run this code on submitting the form, especially since no other events happen between the "submit" button click and submission. Here is the code:
$('form').submit(function (e) {
e.preventDefault();
//If Corporation is selected as business type
if ($('#businessStructure').val() == "Corporation") {
//Checks CEO signature present
if ($("#signImage").length == 0 || $("#signImage").attr("src") == "") {
alert("Please sign and save your signature in the CEO signature pad");
$("#ceoError").show();
}
else {
//all good, an image exists
$('form').submit();
}
}
//If Sole Proprietor is selected as business type
else if ($('#businessStructure').val() == "SoleProprietor") {
//Checks CEO signature present
if ($("#signImage").length == 0 || $("#signImage").attr("src") == "") {
alert("Please sign and save your signature in the CEO signature pad");
$("#ceoError").show();
}
//Checks partner1 signature present
if ($("#signImage1").length == 0 || $("#signImage1").attr("src") == "") {
alert("Please sign and save your signature in the first partner signature pad");
$("#partner1Error").show();
}
else {
//all good, an image exists
$('form').submit();
}
}
else {
//Checks CEO signature present
if ($("#signImage").length == 0 || $("#signImage").attr("src") == "") {
alert("Please sign and save your signature in the CEO signature pad");
$("#ceoError").show();
}
//Checks partner1 signature present
if ($("#signImage1").length == 0 || $("#signImage1").attr("src") == "") {
alert("Please sign and save your signature in the first partner signature pad");
$("#partner1Error").show();
}
//Checks partner2 signature present
if ($("#signImage2").length == 0 || $("#signImage2").attr("src") == "") {
alert("Please sign and save your signature in the second partner signature pad");
$("#partner2Error").show();
}
else {
//all good, an image exists
$('form').submit();
}
}
});
This is the first time I have done a concurrent event with a MVC app form submission. Is there a different approach I am unaware of?
As others have mentioned in the comments, you are calling the submit method on the form inside the code which will make the entire code executes again including your else condition, which in turn calls the submit again, hence causing the infinite submit events
else {
//all good, an image exists
$('form').submit();
}
To fix this, you can wire up your event using the button id inside the form
<form action="someUrl" method="post">
<button type="button" id="btn-save">Save</button>
</form>
and the script will be
$("#btn-save").click(function(e){
e.preventDefault();
// your existing code
});
To get a refernce to the form, I would recommend getting the form using relative selectors. In this case, closest() method will be handy
$("#btn-save").click(function(e){
e.preventDefault();
var $form = $(this).closest("form");
if(yourValidationCodeGoesHere)
{
}
else
{
$form.submit();
}
});
So I have two fields in my webpage, one for telephone number and the other for email address, I need to make either one of them required to be filled by using JavaScript NOT jQuery. Most of the answers I found here are for jQuery, any solutions with JavaScript would be much appreciated. Thanks!
function User_one(){
var phone = document.getElementById('PhoneText2').value;
var mail = document.getElementById('EmailText1').value;
if (phone && mail == ""){
alert("An error occurred.");
}else{
return false;
}
}
Update with actual code
Here's how I'd do it
(function () {
document.getElementById('myForm').addEventListener('submit', function(event){
// Get the length of the values of each input
var phone = document.getElementById('PhoneText2').value.length,
email = document.getElementById('EmailText1').value.length;
// If both fields are empty stop the form from submitting
if( phone === 0 && email === 0 ) {
event.preventDefault();
}
}, false);
})();
Since you haven't supplied any code for us to work with, I'll answer in pseudo-code:
On form submission {
If (both telephone and email is empty) {
throw validation error
}
otherwise {
submit the form
}
}
If you show me your code I'll show you mine :-)
I am trying to make a simple web application. In my login page I have a form with a text field, a password and a submit button. Form submission is prevented if either fields are empty. This is the script I use:
function checkLoginCredentials() {
var usernameFormValue = $("#usernameForm").val().trim();
var passwordFormValue = $("#passwordForm").val().trim();
var validated;
$("#loginForm").submit(function(event){
if (usernameFormValue === "" || passwordFormValue === "") {
$("span").html("Enter a username or password");
validated = false
} else {
validated = true;
}
return validated;
});
}
However, I noticed that once the script runs and form submission is prevented, the user can no longer make an attempt to log in again. The only alternative I can think of is to have ALL validations done by my login servlet and utility classes. Is there a way around this or must validations of invalid entries like empty strings be done by my Java Classes?
The issue here is how you are assigning the validation code. You have a checkLoginCredentials and when you call it you read the form values. And than you add a form submission. You should add the reading of the textbox values inside of the submit method, not outside.
$("#loginForm").submit(function(event){
var usernameFormValue = $("#usernameForm").val().trim(),
passwordFormValue = $("#passwordForm").val().trim(),
validated;
if (usernameFormValue === "" || passwordFormValue === "") {
$("span").html("Enter a username or password");
validated = false
} else {
validated = true;
}
return validated;
});
I have a commenting system in PHP, in which there is loop to fetch articles. every article has a comment form which needs to be validated for null values.
Now problem is there is no limit to the number of these forms and ID of each form is coming from database. I want to validate each form but without writing the script multiple times.
How can i validate the form field for null value without writing script again & again.
Can i create a loop kind of thing in my script which check the field for null values.
My script is like this -
function validatecomments()
{
nums = ["1", "2", "3", "4"];
text = "commentform"; //form id is like this - commentform1, commentform2, ...
for (var i = 1; i < nums.length; i++) {
text = text + nums[i]; //to create it like form id
if (document.text.comment_emp_id.value=="")
{
alert("Please enter the Employee ID");
document.text.comment_emp_id.focus();
return false;
}
if (document.text.comment.value=="")
{
alert("Please give some Comments");
document.text.comment.focus();
return false;
}
}
}
this is snapshot of the comment form. here are 2 forms with POST button. Problem is i have a number of such forms in a page and i have to check them for null values. I am being forced to write script code multiple times.
Can anyone help me out.
you are not sending correct value to the script. try this
<form name="commentform<?php echo $your_id?>" action="" onSubmit="return validatecomments(this);" method="post">
in your script
function validatecomments(f)
{
if (f.elements['comment_emp_id'].value=="")
{
alert("Please enter the Employee ID");
f.elements['comment_emp_id'].focus();
return false;
}
else if (f.elements['comment'].value=="")
{
alert("Please give some Comments");
f.elements['comment'].focus();
return false;
}
}
May be it helps you.
I have a forgot password form. It has two fields 1) email and 2) mobile. So what I need is a validation for it. like both field should not be empty, both field should not be filled, any one only should be filled. email should be in email format and mobile should only contain numbers.
javascript Code:
function validate_fgtmgrpwd(){
var adminid=document.f_mgr_password.mgrid;
var adminmobile=document.f_mgr_password.mgrmobile;
var mgr_length=document.f_mgr_password.mgrmobile.value;
if ((document.f_mgr_password.mgrid=="Ex: ManagerID#Email.com")||
(document.f_mgr_password.mgrid==""))
{}
{document.getElementById("validationMessage").innerHTML=" <font color='#FF0000'>Error: </font> Please Enter Either Email Id Or Mobile No:!";
popup('validationPopup');
mgrid.focus();
return false;
}
}
You should do the validation server side, not client side. There are always ways to get around your javascript form validation.
So you should check/validate the POST values in your php script, and act accordingly.
With html5 you can define an input type="email" for your email field ( so it parse properly inserted email ) and an input type="tel" for your mobile phone field. So, set the clear field at onfocus event for the other field. this should works fine.
Try this:
function validate_fgtmgrpwd() {
var adminid = document.f_mgr_password.mgrid,
adminmobile = document.f_mgr_password.mgrmobile,
emailExp = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/gi,
phoneExp = /^[0-9\-\+]{9,15}$/gi;
if(!adminid.value.length && !adminmobile.value.length){
alert("At Least one field is mandatory!");
adminid.focus();
return false;
} else {
if(adminid.value.length && !emailExp.test(adminid.value)){
alert("Enter a valid email");
adminid.focus();
return false;
} else if(adminmobile.value.length && !phoneExp.test(adminmobile.value)) {
alert("Enter a valid phone number");
adminmobile.focus();
return false;
} else {
return true;
}
}
}
For HTML5 supporting browsers, native validation will work and for other browsers, custom validation will work.
jsfiddle: http://jsfiddle.net/MR6bD/2/