choosing order of validation methods on submit - javascript

I am using a validation plugin for my form but after the standard validation i want to add my own methods one of them is a Ajax function which checks if email already exists.
Both work but if i for example enter a email it does the Ajax method, where i want to put a redirect.
the problem is that even if not all fields are filled it always redirects. It has to check al standard validation first, then do the ajax if all is OK then submit how do I do this ?
$( "#registration-form" ).submit(function( event ) {
//vars
var contactemail = $('#contactemail').val();
var contactpassword = $('#contactpassword').val();
//Global validation
$.validate({
onError : function() {
//alert('Validation failed');
return false;
}
});
//If User create - check if user exists
if($('#contactemail').length && $('#contactemail').val().length && $('#contactpassword').length && $('#contactpassword').val().length)
{
//Check if can create user
$.post(jssitebaseUrl+'/ajaxFile.php',{'contactemail':contactemail,'action':'checkOrderEmailId'}, function(output){
//alert(output);
if(output == 'UserExist' && contactpassword !=""){
$("#errors").show();
$('#errors').html('<p class="i">Can not create account</p>');
$('html, body').animate({scrollTop:0}, 'slow');
return false;
}
else if(output == 'CanCreateAccount' || (output == 'UserExist' && contactpassword =="")){
alert("Maak een guest order aan")
//redirect...
document.checkoutform.submit();
}
});
}
event.preventDefault();
});

Try checking if form is valid before posting:
if ( $("#formId").valid() ) {
// ajax call
}

Related

Submit data to Google script and keep user on my site (validation conflict)

I have a form that submits data to a Google script. Currently my users are sent to Google's page when submitting a form. I tried adding an ajax script to keep them on the page after submitting but when I do that my validation script doesn't work. When I try to combine them neither script works. One of the issues is that the "post" url is decided using a php script (due to Google,s limitations) Below is my code, any help would be appreciated. Thank you!
Submit information to Google and keep user on my page:
$('#agentForm').submit(function(e){
e.preventDefault();
$.ajax({
url:'<?php echo $actionURLs[$counter]; ?>',
type:'post',
data:$('#agentForm').serialize(),
complete:function(){
//whatever you wanna do after the form is successfully submitted
window.location = "agents.php?agentID=<?php echo $_GET['agentID']; ?>&email=<?php echo $_GET['email']; ?>&action=submitted";
}
});
});
Validation:
// Wait for the DOM to be ready
function validateForm()
{
var pax = jQuery('input[name="passengers"]:checked').length > 0;
var rph = jQuery('input[name="reservation"]:checked').length > 0;
var validationPassed = true;
var msg = '';
//console.log(pax);
//console.log(rph);
//console.log(jQuery('#mco').val());
//console.log(jQuery("input:radio[name='flights']").is(":checked"));
//console.log(jQuery("input:radio[name='iscorrect']").is(":checked"));
if(!pax){
validationPassed = false;
msg +='Please select at least one passenger.</br>';
}
if(!rph){
validationPassed = false;
msg +='Please select at least one segment.</br>';
}
if(jQuery('#mco').val() != '' && !jQuery.isNumeric(jQuery('#mco').val())){
validationPassed = false;
msg +='MCO Amount must be a numeric value.</br>';
}
if (!jQuery("input:radio[name='flights']").is(":checked")){
validationPassed = false;
msg +='Are all flights being flown?</br>';
}
if (!jQuery("input:radio[name='iscorrect']").is(":checked")){
validationPassed = false;
msg +='Is the total correct?</br>';
}
else if(jQuery('input[name=iscorrect]:checked').val() == 'INCORRECT' && jQuery('#correct_amount').val() == ''){
validationPassed = false;
msg +='Please specifiy the correct amount.</br>';
}
else if(jQuery('input[name=iscorrect]:checked').val() == 'INCORRECT' && jQuery('#correct_amount').val() != '' && !jQuery.isNumeric(jQuery('#correct_amount').val())){
msg +='Correct amount must be a numeric value.</br>';
}
if(!validationPassed){
jQuery('.errors').show();
jQuery(window).scrollTop(jQuery('.errors').offset().top);
}
jQuery('.errors').html(msg);
return validationPassed;
}
jQuery( document ).ready(function() {
jQuery("input[name='iscorrect']").click(function(){
jQuery('#correct_amount').val('');
/*if(jQuery('input[name=iscorrect]:checked').val() == 'INCORRECT'){
jQuery("#correct_amount").prop("readonly", false);
}
else{
jQuery('#correct_amount').val('');
jQuery("#correct_amount").prop("readonly", true);
}*/
});
jQuery("input[name='correct_amount']").click(function(){
jQuery('#INCORRECT').prop('checked', true);
});
});
I think your validation is not working because you have stopped propagation of the event in your JavaScript first code with e.preventDefault().
Try to call validateForm() directly inside your first submit event listener, like that:
$('#agentForm').submit(function(e){
validateForm();
e.preventDefault();
$.ajax({
url:'<?php echo $actionURLs[$counter]; ?>',
type:'post',
data:$('#agentForm').serialize(),
complete:function(){
//whatever you wanna do after the form is successfully submitted
window.location = "agents.php?agentID=<?php echo $_GET['agentID']; ?>&email=<?php echo $_GET['email']; ?>&action=submitted";
}
});
});

Mousedown still submitting form, when it should not

hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});

How to perform validation for Onclick Javascript Custom button

I have the code below and I would like it to perform multiple field validation and give alert on each field when it is incomplete. Scenario: If I use the code without the validation and associated alerts it works 100%, when I include the validation the code goes through each step and alert and ultimately fails on the last bit to execute and flag a field as 'true' and gives error of 'Invalid or unexpected token'. Any help would be welcome
{
!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")
}
var x;
if ('{!Case.Trigger_Submit_Spark__c}' == true || '{!Case.Spark_Service_Desk_Ref__c}' != "") {
alert('You are unable to submit request, as this request has already been submitted to Spark')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as Spark Service Request Type and Request note are blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' != "") {
alert('You are unable to submit request, as Spark Service Request Type is blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' != "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as the Spark Request Note is blank')
} else {
if ('{!Case.Trigger_Submit_Spark__c}' == false && confirm('Do you want to submit this request?\n\nBy submitting this request the following will occur:\n 1. Case Status changed to Escalated to Tier2\n 2. Escalation Group = Spark\n 3. Email sent to Spark (Remedy)\n 4. Note placed in SalesForce chatter feed\n\nPlease check chatter feed to confirm that request has been sent') == true) {
x = "OK";
var c = new sforce.SObject("Case");
c.id = '{!Case.Id}'
c.Trigger_Submit_Spark__c = true;
result = sforce.connection.update([c]);
if (result[0].success === "true") {
window.location.reload();
} else {
alert("An Error has occured. Error: " + result[0].errors.message);
}
}
}
}
}
}

On input does not work after preventDefault

I am making simple auth form with some messages for user while he is typing the username/email in the input. Before form submission code works just fine, but after I submit the form (with preventDefault) this 'input-checker' stops working. Can anyone tell me why and how to make it work?:-)
var reValidEmail = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
$("#auth-input").on('input', function () {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
if (!reValidEmail.test(document.getElementById("auth-input").value)) {
$("#login-comment").text("Please enter valid email");
} else {
$("#login-comment").text("");
}
}
});
$("#log-in-form").submit(function (e) {
e.preventDefault();
if ( document.getElementById("auth-input").value.length > 0
&& ( document.getElementById("auth-input").value.indexOf("#") == -1
|| ( document.getElementById("auth-input").value.indexOf("#") + 1
&& reValidEmail.test(document.getElementById("auth-input").value)
)
)
) {
//some ajax request
} else {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
$("#login-comment").text("Please enter valid email"); //does not hide after form submission and input change for correct one
} else {
$("#login-comment").text("Please enter username or email"); //does not hide after form submission and input change for correct one
}
}
});

How to display error in real-time on HTML form? (Javascript included)

I'm trying to show errors in real time on my registration form, instead of being redirected to another page (register.php).
The index page on my site has a sign-up link which opens a popup registration form (registration.HTML) in a new window. When a user submits this form
it calls on register.PHP as an action. Inside register.php there is a line of code:
js_include('js/register.js');
This javascript checks that certain data is submitted correctly within registration.html. I'd like this check to be performed before submitting the form
and causing it to redirect to register.php. I only need it to direct to register.php if javascript says everything is good.
You can test this yourself here If you click "sign up" in the top-right corner, and type in gibberish as the email and press Enter, it will redirect to register.php and show the error at the bottom (if you scroll down). I'd like this error to be displayed on the registration form.
I tried including the js below within some script tags on my html page, but it still redirects me.
Here is register.js, all feedback is welcome! Thank you
$(document).ready(function() {
$('.formFieldWarning').hide();})
function checkRegisterFormSubmit() {
$('.formFieldWarning').hide();
var errors = 0;
// Check the user name
if($('#username').val() == '') {
$('#username_warning1').show();
errors++;
} else {
if ($('#username').val().length < 2 ) {
$('#username_warning2').show();
errors++;
}
}
// Check the password
if ($('#password').val().length < 2 ) {
$('#password_warning1').show();
errors++;
} else {
if ($('#password').val() == $('#username').val() ) {
$('#password_warning2').show();
errors++;
}
}
// Check the password_verification
if ($('#password_verification').val() != $('#password').val() ) {
$('#password_verification_warning1').show();
errors++;
}
// Check the email address
if($('#email').val() == '') {
$('#email_warning1').show();
errors++;
} else {
if ($('#email').val().search(/^\w+((-|\.|\+)\w+)*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,63}$/) == -1) {
$('#email_warning2').show();
errors++;
}
}
if (errors != 0) {
$('#form_not_submit_top').show();
$('#form_not_submit_bottom').show();
return false;
} else {
return true;
}
}
Here is an example of how to test a form field using jQuery's blur() function -
$('input[name="foo"]').blur(function() {
var currentValue = $(this).val();
var testValue = 'crumple';
if(currentValue != testValue) {
$(this).next('span').html('FAIL');
} else {
$(this).next('span').html('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="foo" type="text" /><span></span>

Categories