JavaScript form validation issue - submit has to be clicked twice - javascript

JavaScript code of validation- https://freedigitalphotos.net/images/js/judd-validate.js
We have some new forms on our website which have client side JavaScript validation.
The validation is triggered when the user "defocuses" from the form fields. The validation is a combination of AJAX (checking database for valid user names etc) and JavaScript (checking fields not blank, or contain expected data).
The user has to click the form submit button twice to send the form. It seems that the first click is triggering the field validation but not submitting the form. Clicking for a second time successfully completes the form.
Go to- https://freedigitalphotos.net/images/recover_password.php
Type arifkpi#gmail.com in the email field, and then immediately hit submit. Again, notice that the first click merely validates the input, using AJAX it is checking the email address is in the database. A second click is required.
I want to fix this, so everything will work with a single click.

Instead of calling Ajax validations on focustout event, you can call it on click of your button and if Ajax returns true result then submit form programatically. Refer few sample code lines:
Html Part:
<form method="post" id="registration_form" name="registration_form" action="register.php">
EmailId: <input type="text" id="email_id" name="email_id">
<label class="error" for="username" id="globalErrorUsername"></label>
Username: <input type="text" id="username" name="username">
<label class="error" id="globalErrorEmail"></label>
<button type="button" id="register_btn" name="register_btn">Register</button>
</form>
Js Part:
$("#register_btn").click(function() {
//.valid function is useful when you are using jquery Validate library for other field validation
if ($('#registration_form').valid()) {
var email_id = $('#registration_form').find('#email_id').val(),
username = $('#registration_form').find('#username').val();
$.ajax({
beforeSend: function() {
$('#globalErrorUsername').html('');
$('#globalErrorEmail').html('');
}, //Show spinner
complete: function() { },
type : 'post',
url : 'check-user-existence.php',
dataType :'json',
data : 'email_id=' + email_id + '&username=' + username,
success:function(response) {
if(response.success == 1) {
//submit the form here
$("#registration_form").submit();
} else if (response.error == 1) {
if(response.details.username != undefined) {
$('#globalErrorUsername').show();
$('#globalErrorUsername').html(response.details.username);
}
if(response.details.email_id != undefined) {
$('#globalErrorEmail').show();
$('#globalErrorEmail').html(response.details.email_id);
$('#email_id').focus();
} else {
$('#username').focus();
}
}
}
});
} else {
return false;
}
return false;
});

Related

How do I submit a form if AJAX validation is false?

I’m trying to validate a PromoCode prior to form submission. I AM able to do that but if the result is false, I am unable to submit the form unless the input field has been cleared. I’m a self-taught hobby coder and don’t really understand JS, AJAX or cfcomponent (this is my first shot at all of it.) I’ve had a great deal of help getting to this point. All additional help is greatly appreciated.
SUMMARY:
If the PromoCode the user types into the text field matches what’s stored in the DB… all is good. They submit the form and get the discount.
If the PromoCode the user types into the text field does NOT match, they get the message “Sorry, that is not a valid promo code” but cannot submit the form unless the text field has been cleared.
I need the user to be able to submit the form if the PromoCode is invalid… they just wouldn’t get the discount. We just told them it was invalid so they’re on their own. I'd hate to have the user not understand this and leave the site frustrated without registering.
JAVASCRIPT
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
promocode: {
remote: {
url: "/components/promoCodeComponent.cfc?method=validatePromoCode",
data: {
courseId : $("#courseId").val()
}
}
}
},
messages: {
promocode: {
remote: jQuery.validator.format("Sorry, {0} is not a valid Promo Code")
}
},
errorClass: "text-danger",
validClass: "text-success"
});
});
FORM
<form id="signupform" autocomplete="off" method="get" action="">
<!--- demo only --->
Course Id: <input id="courseId" name="courseId" type="text" value=""><br>
Promo Code: <input id="promocode" name="promocode" type="text" value=""><br>
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</form>
CFC
component {
// Note: See Application.cfc docs on setting application level datasource, i.e. "this.datasource"
remote boolean function validatePromoCode(string courseId, string promoCode) returnFormat="json"{
local.qPromoCode = queryExecute(
" SELECT COUNT(*) AS TotalFound
FROM Courses
WHERE Id = :courseId
AND PromoCode = :promoCode
AND LEN(PromoCode) > 0
"
, {
promoCode = { value=arguments.promoCode, cfsqltype="varchar" }
, courseId = { value=arguments.courseId, cfsqltype="integer", null=!isNumeric(arguments.courseId) }
}
, { datasource=“My_DataSource_Name" }
);
;
if (local.qPromoCode.TotalFound gt 0) {
return true;
}
return false;
}
}

Validate multiple input type="email" using Javascript

I have one form which contain multiple email field so this email to be submitted in database but before that it should validate to avoid duplication, (multiple email fields generated by click on add more button which is present in form ).
I have written ValidateEmail script to avoid duplication however it will work for only one email field but not successfull for multiple email field.
issue:
1) if we type email id in first field it will go for validation and check email exist or not if exist disable submit button if not exist enable button.
2) if we type type email id in second field and after validation it return email not exist then it will enable submit button however in first email field contain duplicate email.
3) if all email fields not contain duplicate values then only enable submit button else it should remain disabled..
<form>
<div>
<input type="email" name="email[]" class="email" onblur="validate_email(this)" /> // initially single filed
// This additional email fields created when click on add more button
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
</div>
<button class="add_more">Add more</button> // this will append extra email fileds
</form>
<script>
// This is the script it will check whether email already exist or not
function ValidateEmail(data) {
var email_id = data.value;
$.ajax({
type: "POST",
url: "<?= base_url('controller') ?>",
data:{
email_id:email_id
},
dataType: 'json',
success: function (response) {
if(response.exist){
// disable submit button and show error
}
else{
//enable submit field and hide error
}
},
error: function (jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
</script>
If you're using jQuery for this, you can use event delegation for dynamic inserted/removed element. As of now, those will be the email inputs.
Basically the idea here is:
Get the value of last changed/onblur input element.
Validate for existing email on server side (asynchronous check)
Scan through the current available email inputs, then validate and match each value with the Current Email in step (1).
If found, add a error class to the existing email field
Otherwise, add a valid class to the existing email field
You dont need to pass onblur="validate_email(this)" , this can be done in jquery.
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
function isEmail(email) {
// eslint-disable-next-line no-useless-escape
return RegExp(/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i).test(email);
};
function asyncEmailValidate(email) {
return new Promise(function(resolve, reject) {
if (data.includes(email))
return reject('Found duplicated')
return resolve(true);
})
}
$(document).ready(function() {
$(document)
.on('blur',"input.email", function(e) {
// Current email input
var currentEmail = e.target.value,
$emailNode = $(this),
isValid = true;
// Validate email
if (!isEmail(currentEmail))
return;
// Validate email on server side first,
// If found no existing email, then check
// siblings email for duplicates
var serverResult = asyncEmailValidate(currentEmail);
serverResult
.then(function(result) {
// There's no existing email with the inputed email. Now
// look up on other available email inputs fields, except
// the current one, and validate with the current email value
var siblingsEmailInputs = $("input.email").not($emailNode);
if (!siblingsEmailInputs)
return;
if (siblingsEmailInputs.length > 0) {
siblingsEmailInputs.each(function(index) {
console.log('input : ', $(this).val())
if ($(this).val() !== "" && $(this).val() === currentEmail) {
isValid = false;
}
});
}
// Finally update the state for the current field
if (isValid) {
$emailNode.addClass('is-valid');
} else $emailNode.addClass('is-error');
})
.catch(function(error) {
$emailNode.addClass('is-error');
console.log('error:', error);
})
});
})
.email.is-error {
border: 1px solid red;
}
.email.is-valid {
border: 1px solid green;
}
.email {
width: 300px;
margin: 5px;
height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
</pre>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
Those are just the basic way for you to handle email validation and duplicated emails. I think you can take it from here to work on your submit logic.
One quick note, you should leave the ajax submitting process in a separate function, not mixing up with validation process, it will be clearer.
Hope this help
Link working sample: https://codepen.io/DieByMacro/pen/jOOdWMr
Updated:
- I haven't used ajax with jQuery for a while so I'm not sure about the correct syntax, so I've replaced it with a Promised call which works the same as you make an asynchronous request. You can follow the updated version for your reference.

Prompt recently entered values for forms without getting submitted and not ajax posting to any urls

I am running a simple Embedded web-server where a form needs to be filled and the data can be submitted in 3 different ways for a Truck weighing operation. As i am having 3 different buttons to submit the data through an ajax call to a lua webserver i don't want the form gets submitted in default way.
<form id="formTruck" class="form-group">
<label class="form-label" for="reg-num">Rego:</label>
<input class="form-input" type="text" id="rego">
<label class="form-label" for="product">Product:</label>
<input class="form-input" type="text" id="product">
<label class="form-label" for="valuePT">Preset Tare</label>
<input class="form-input" type="text" id="valuePT">
<input id="dump-submit" style="display:none" value="Submit_Dump" type="submit">
</form>
<div id="weighInOutGroup">
<button id="weighIn" onclick="weigh(this.id);">WEIGH IN</button>
<button id="weighOut" onclick="weigh(this.id);">WEIGH OUT</button>
<button id="weighInPt" onclick="weigh(this.id);">WEIGH IN (PT)</button>
</div>
I have JS function to do the ajax request depends on the button clicked
function weigh(type) {
var weighData = {};
if (type == "weighIn") {
$.ajax({
//ajax request
},
});
} else if (type == "weighInPt") {
//ajax request
} else if (type == "weighOut") {
//ajax
}
};
Also i have used following jquery function to prevent pressing enter navigating to default action
$("#formTruck").submit(function(e){
e.preventDefault();
console.log("weighIn submit prevented")
});
but by doing this i couldn't get the recent inputs prompted on text input fields, as the form is not actually submitted in default action.
Can anyone suggest me a way to achieve this without doing any posts or navigating to any pages?
i don't understand why you use 3 send buttons, use instead a radio buttons, in the jquery submit add your if's and for catch the form data use $("#formTruck").serialize()
$("#formTruck").submit(function(e){
console.log("weighIn submit prevented");
let data = $("#formTruck").serialize() ;
if ($("#rdWeighIn").prop("checked")) {
$.ajax({ data: data, ...
} else if ($("#rdWeighOut").prop("checked")) {
$.ajax({ data: data, ...
} else if ($("#rdWeighInPt").prop("checked")) {
$.ajax({ data: data, ...
} else {
//
}
return false;
});

Refresh jquery form after submission not working

For one of my websites, I am designing a HTML form with jquery and PHP for sending the data through email.
The Jquery, checks for the empty /blank fields and sends alerts for each filed.
Once the form is submitted with full data, it sends success alert and send the input data through PHP.
Till this point the code works fine.
Once the data is submitted & success alert is shown, I want the html form to be refreshed / reloaded.
But this this not happening, as the form remains with the pre-entered data.
Kindly help me in this please. My Jquery & HTML form is given below.
JQUERY-CODE (with google libs 2.2)
JQUERY CODE
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '') {
alert(" Please fill your name");
} else if (email == '') {
alert("Please fill your email");
} else if (message == '') {
alert("Please Fill message");
} else { alert("Your form submitted. We will contact you soon.");
$.post("xxx.php", { // To php file.
name: name,
email: email,
message: message
}, function(data) {
$("#returnmessage").append(data);
if (data == "Your form submitted. We will contact you soon.") {
$("#form")[0].reset(); // To reset form fields on success.
}
});
}
});
});
HTML FORM CODE:
<form id="form" method="post" action=" ">
<h4>FEED-BACK FORM</h4>
<p id="returnmessage"></p>
<label>Name: </label>
<input type="text" id="name" /><br>
<label>Email: </label>
<input type="text" id="email" /><br>
<label>Message: </label>
<input type="text" id="message" /><br>
<input type="button" id="submit" value="Submit"/>
</form>
check below js
if (data == "Your form submitted. We will contact you soon.") {
document.getElementById('form').reset(); // To reset form fields on success.
}
Or
if (data == "Your form submitted. We will contact you soon.") {
$('#form').find("input[type=text]").val(""); // To reset form fields on success.
}
you can clear the input fields by setting its value to ""
$("#name").val("");
$("#email").val("");
$("#message").val("");
The problem is most likely with your if statement. The line $("#form")[0].reset(); is correct, move it above the if statement to see it working.

Prevent Form from Submitting if there are Errors

Before I get into the problem details, I still need to tell you about this form I am creating. I have a Registration form and once the user submits the form by clicking the Submit button, it will NOT go directly to a Successfully Registered page. The user will be seeing a Confirmation page prior to that. In this page, the user will see all the data he inputted for him to review. Below it are the Confirm button and the Return button (if user still likes/needs to edit his details, it will then show the form for him to edit once this button is clicked). But here's the thing, the Registration form page and the Confirmation page are in just the same page. What I did is that when the user submits the form, it will hide some elements including the Submit button and then just show the details he inputted. When the user clicks the Return button on the Confirmation page, it will just then show again the hidden fields so the user can edit his details.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working. I am using bootstrap for my form so when there are errors, the input fields' borders would turn red and would obtain a class has-error. Here's what I did:
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
But again, it is not working. I also googled some jQueries like the .valid() and .validate() functions but I'm not really sure about it and also didn't work for me.
I also did this code where the Submit button should disable when required fields are still empty. And it is perfectly working:
$('#submit').attr('disabled',true);
$('input[id^="account"]').keyup(function() {
if(($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0)) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
I hope you understand my problem. I will make it clearer if this confuses you.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working.
When is it checking for errors? It needs to disable the submit button at the same time it is checking for errors. Your code doesn't work because there's no event telling it WHEN to execute. WHEN do you want submit button to be disabled?
Do you want it triggered when the field is validated or when the form is submitted?
You can't really tie it to the submit button unless you want to click it first to validate the form fields, and then again to submit validated fields. Then you'll need to figure out how to tell it that it's been validated like by a class, maybe? Only accept inputs that hasClass('valid')?
below are the changes
$(".form-group").find("td").each(function() {
if($(this).hasClass('has-error')) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
Try the following
$('#submit').click(function(){
var error = false;
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
error = true;
return false; //break out of .each
}
});
return !error;
});
You can achieve this by maintaining 2 sections.
1. Form section
<form id="form1">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="button" id="confirm" value="Confirm" />
</form>
2. Confirm section
<div id="disp_data" style="display: none;">
<lable>Name: <span id="name_val"></span></lable>
<lable>Email: <span id="email_val"></span></lable>
<input type="button" id="return" value="Return" />
<input type="button" id="submit" value="Submit" />
</div>
You have to submit the form by using js submit method on validating the form in confirm section (When the user clicks on submit button)
$("#submit").click(function(){
var error_cnt = false;
if($("#name").val() == '') {
error_cnt = true;
alert("Enter Name");
}
if($("#email").val() == '') {
error_cnt = true;
alert("Enter Email");
}
if(error_cnt == false) {
$("#form1").submit();
} else {
$("#disp_data").hide();
$("#form1").show();
}
Demo
You have to prevent the form from sumition by return back a boolean false so that it will stop the execution.
$('#submit').click(function(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
if(!ret) return false;
});
If you want to disable the submit button in case of any error you need to monitor the changes of each input fields. so better to give a class name to all those input fields like commonClass
then
function validation_check(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
return ret;
}
$("#submit").prop("disabled",true)
$(".commonClass").change(function(){
if(validation_check()){
$("#submit").prop("disabled",false)
}
else {
$("#submit").prop("disabled",true)
}
});
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error. I've added fiddle you can try.
HTML FORM
<form action="" method="" onsubmit="return dosubmit();">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="submit" value="Submit" />
</form>
JAVASCRIPT
function dosubmit() {
if(false) { //Check for errors, if there are errors return false. This will prevent th form being submitted.
return false;
} else {
return true;
}
}
Let me know if this fixes your issue.

Categories

Resources