JavaScript Validation error? - javascript

I have been working on a JavaScript validator, but for some reason, evalid always returns as false even if it has passed validation... this is a bug as if evalid is false, the form doesn't submit.
function signup_validate()
{
document.getElementById("email_error").innerHTML = "";
document.getElementById("password_error").innerHTML = "";
evalid = false;
pvalid = false;
email = null;
pass = null;
confpass = null;
email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
atpos=email.indexOf("#");
dotpos=email.lastIndexOf(".");
pass=document.forms["signup_form"]["pass"].value;
confpass=document.forms["signup_form"]["confpass"].value;
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
}
else
{
$.post('/resources/forms/signup.php',{email: email}, function(data){
if(data.exists){
document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
}
else
{
evalid = true;
}
}, 'JSON');
}
if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
{
pvalid = true;
}
else
{
document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
}
alert(evalid);
if (evalid == true && pvalid == true)
{
document.getElementById("signup_form").submit();
}
else
{
return false;
}
}
What could I have missed?

The only moment when you set "evalid" true is inside a function that runs asynchronously. In other words, by the time you set "evalid" true the main function has already reached the end.
You Could try to use $.ajax instead of $.post and use the parameter async:false
Try something like this:
$.ajax({
type: 'POST',
url: '/resources/forms/signup.php',
data: {email: email},
success: function(response){
//your function here
},
dataType:'JSON',
async:false
});

Related

Javascript validation works...and fails

I have the following Javascript code in my web page that SHOULD ensure data validation and then (if the form is valid) submit the data to an AJAX call:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
}
});
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
The problem is, the validation works, but it doesn't. When the form fields are not valid, it hits this block:
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
and the alert is displayed. The very next line should force the function to exit, stopping execution of any remaining code, but for some reason it doesn't. Instead, the remainder of the code executes as if the form is valid, and the alert for the AJAX failure pops up.
Why does the 'return false' not actually force the function to exit, and what am I missing here?
return false is a statement of the anonymous function function (form) {... which is called for each form element. The anonymous function function (event) {... doesn't have a return statement. The filter function in Array.prototype.filter.call(forms, has to return either true or false for each element to work as expected, not false or undefined. You could use e.g. Array.prototype.every and/or Array.prototype.map instead of Array.prototype.filter:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.map.call(forms, function (form) {
if (!form.checkValidity()) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
return true;
}
});
if (!validation.every(el => el)) return false;
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>

Ajax call not working in function

I have one function in java script. I want to send my form in ajax call after validation. I wrote ajax code for this but it's neither working nor giving any error on console even .
What can i do ?
javascript
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$.ajax({
type: "POST",
url: "quoteProcess.php",
data : $('#testform').serialize(),
success: function(data) {
alert(data);
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}

return false not preventing form from submitting

I am trying to validate a field using $.get request. I can see the error message("Plan already present") but the form is getting submitted. I want to prevent form from submitting. Here is my code:
$("#add_plan_subscriptions").submit(function(event) {
var flag = true;
var subdomain_val = $('[name="plan[subdomain_type_id]"]').val();
var plan_val = $('[name="plan[plan_type_id]"]').val();
var plan_name = $('[name="plan[plan_name]"]').val();
var subdomain_type_id = subdomain_val;
var plan_name = $('[name="plan[plan_name]"]').val();
$.get("/plans/check_duplicate_plan",{subdomain_type_id: subdomain_type_id, plan_name: plan_name}, function (response) {
if (response){
event.preventDefault() ;
var element = $('[name="plan[plan_name]"]');
var message = "Plan already present";
addError(element,message)
return false;
}
else{
var element = $('[name="plan[plan_name]"]');
removeError(element)
}
})
if(subdomain_val == ""){
var element = $('[name="plan[subdomain_type_id]"]')
var message = "Please select user type"
addError(element,message)
flag = false;
}
if(subdomain_val != ""){
var element = $('[name="plan[subdomain_type_id]"]')
removeError(element)
}
if(plan_val == ""){
var element = $('[name="plan[plan_type_id]"]')
var message = "Please select plan type"
addError(element,message)
flag = false;
}
if(plan_val != ""){
var element = $('[name="plan[plan_type_id]"]')
removeError(element)
}
if (!flag){
event.preventDefault();
return false;
}
return true;
});
Now $.get calling in async mode before response of GET your form submit function is calling.
So use ajax in sync mode instead $.get
$.ajax({
url: '/plans/check_duplicate_plan',
data: { subdomain_type_id: subdomain_type_id, plan_name: plan_name},
dataType: 'json',
async:false,
type: 'GET',
success: function (response) {
if (response){
event.preventDefault() ;
var element = $('[name="plan[plan_name]"]');
var message = "Plan already present";
addError(element,message)
return false;
}
else{
var element = $('[name="plan[plan_name]"]');
removeError(element)
}
}
})
Steps:
1.Change input type submit to button type
2.Add this line instead of return true in javascript
document.forms["signup"].submit();
I Had a similar problem. Consider a html like this..
<form name="login" action="ValidateLogin">
<button id="SignIn">Login</button>
</form>
Then Submit the form in javascript where you want your form to return true
$.ajax({
> type: "GET",
> url: "ManageForm",
> data: dataString,
> beforeSend: function()
> {
>
>
> },
> success: function(data)
> {
> if (data == 1)
> { alert("data :"+data);
> document.getElementById("errorName").innerHTML = "Sorry! UserName Already Taken";
> flag = 0;
> return false;
>
> }
> else if (data == 2)
> { alert("data :"+data);
> document.getElementById("erroremail").innerHTML = "Email id Already Registered!";
> flag = 0;
> return false;
> }
> else if (data == 3)
> { alert("data :"+data);
> document.getElementById("errorphone").innerHTML = "Phone No Already Registered!";
> flag = 0;
> return false;
> }
> else
> document.forms["signup"].submit();
> }
>
> });
remove your event.preventDefault() ; inside your $.get function and add event.preventDefault() ; or return false; in your submit function if you just want to prevent the form from submitting
based on jquery documentation http://api.jquery.com/event.preventdefault/
event.preventDefautl(); is called, the default action of the event will not be triggered.
therefore we call this method your submit function will stop triggering the default action
Hopes that helps you understand it :)
You are only preventing the form from submitting when there is a response or subdomain. You need to add event.preventDefault() at the top of the event callback.
$("#add_plan_subscriptions").submit(function(event) {
event.preventDefault();
var flag = true;
The reason why the form get submitted is because in the last two lines of the code you posted it you return true;
Make it return false;
The last two lines of the code you posted is like this
return true;
});
instead make it like this
return false;
});
and also try removing your return true; in that exact line and replace it with event.preventDefault();

submit return false always in jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
this is my code here if(flag=="no") not working, the flag value is not changing, always it prevent default. is there any mistake in my code. ajax return are correct.
$(document).ready(function() {
$('#submit').click(function(event) {
var captcha = $("#captcha").val();
var flag = "no";
if (captcha == '') {
alert("Fill Captcha Field");
event.preventDefault();
} else {
var dataString = captcha;
$.ajax({
type: "POST",
url: "verify.php",
data: {
code: captcha
},
success: function(data) {
if (data == "no") {
alert("Invalid Captcha");
} else {
flag = "yes";
}
}
});
}
if (flag == "no") {
return false;
} else {
return true;
}
});
});
You can try this one, its working example.
var jqXHR = $.ajax({
url: "verify.php",
type: "POST",
data: {code: captcha},
async: false,
success: function (data) {
}
});
if(jqXHR.responseText=="no")
{
alert("Invalid Captcha");
}
else
{
flag="yes";
}
if(flag=="no")
{
return false;
}
else{
return true;
}
It will return after the successfully returning data from ajax request
By default javascript requests are sent asynchronously. when ajax is call take time to get response javascript execute next code. here in your code it is same issue. use below code
$(document).ready(function() {
$('#submit').click(function(event) {
var captcha = $("#captcha").val();
var response ;
if (captcha == '') {
alert("Fill Captcha Field");
event.preventDefault();
} else {
var dataString = captcha;
response = $.ajax({
type: "POST",
url: "verify.php",
data: {
code: captcha
},
success: function(data) {
}
}).responseText;
}
if (response == "no") {
alert("Invalid Captcha");
return false;
} else {
return true;
}
});
});

Jquery form validation with ajax

i need to check if username exist. If it exist, I increment a variable "form_error".
If "form_errors" is > 0, then i stop code with return false.
But, when i make an Ajax call, i cannot increment this variable. Probably is it a scope / visibility problem?
So, in the case that i have an error on username, my form_errors will be forever 0 and form is submit...
How i can increment that form_errors?
Thank you to all, I leave a piece of code
$('#add-sponsor').submit(function() {
var form_errors = 0;
var username = ('#username').val();
$.ajax({
url : location.protocol + '//' + location.host + '/commands.php?action=check-username',
data : {
username : username
},
type : 'post'
}).done(function (result) {
if (result=='false') {
$('#username').parent().addClass('has-error');
$('#username').parent().removeClass('has-success');
$('#username').parent().next('.help-block').text('Questo username già esiste');
form_errors++;
} else {
$('#username').parent().addClass('has-success');
$('#username').parent().removeClass('has-error');
$('#username').parent().next('.help-block').text('');
}
}); // ajax
if (form_errors > 0) {
return false;
}
console.log(form_errors); // <- this is forever 0
}
$.ajax function is asynchronous so will continue execution of
if (form_errors > 0) {
return false;
}
before the done function is executed.
if (form_errors > 0) {
return false;
}
console.log(form_errors); // <- this is forever 0
You check here if you have errors, and if so, you return...so, the console.log will never be hit, unless you have no errors. Maybe just use...
if (form_errors > 0) {
console.log(form_errors);
}
Your best bet might be to use some sort of variable outside your submit function
eg
var isValid = false;
$('#add-sponsor').submit(function() {
if(!isValid)
{
var form_errors = 0;
var username = ('#username').val();
$.ajax({
url : location.protocol + '//' + location.host + '/commands.php?action=check-username',
data : { username : username },
type : 'post'
}).done(function (result) {
if (result=='false') {
$('#username').parent().addClass('has-error');
$('#username').parent().removeClass('has-success');
$('#username').parent().next('.help-block').text('Questo username già esiste');
isValid = false;
$('#add-sponsor').submit();
} else {
$('#username').parent().addClass('has-success');
$('#username').parent().removeClass('has-error');
$('#username').parent().next('.help-block').text('');
isValid = true;
$('#add-sponsor').submit();
}
}); // ajax
return false;
}
return true;
}
Considered using the jQuery validation plugin? You could set up your form using a remote validation rule to check whether the username ist valid. jQuery validation let's you implement your callbacks within the submitHandler or the invalidHandler.
Try this code if you want to test it. Just make sure to include the jquery.validate.js as well as additional-methods.js into your page.
var validator = jQuery("the-sponsor-form").validate({
messages: {
username: {
remote: 'Questo username già esiste'
}
},
rules: {
username: {
required: true,
remote: {
url: location.protocol + '//' + location.host + '/commands.php?action=check-username',
type: 'post',
data: {
username: $('#username').val();
}
}
}
},
submitHandler: function(form) {
alert("now submit the form");
jQuery(form).submit();
}
});

Categories