Mvc validation and loader - javascript

In form post method in MVC view,
if validation fires then loader should not come and display only validations
else no validations fire then loader should come and save the data.
What I have tried:
placed loader on form submit in javascript and disable the button.
$("#frmContact").submit(function (e) {
$(".loading").css("display", "inline");
});
1) loader : Issue is that if validation fires, then loader also come alongwith validations and then need to reload the page and input data.
2) Disable Submit button : If I disable the Submit button on click and if validation fire then after button remains the disable instead enable. So if validation is there then enable the button and if validations are not fire then disable the button.
All this to avoid the duplicate entry as if button enables then if user clicks on submit.

You can do it this way
HTML :
<div id="ajax-loader" style="display:none;">
<img src="<?php echo $loaderSrc; ?>" style="height: 200px;width: 200px;">
</div>
<input type="submit" id = "btnSubmit" value="Submit" name="yt0" onclick="return validateForm();">
In script : (here you can change the fields...i am showing one of my example)
var error_flag = true;
var error_required = true;
$('#btnSubmit').click(function(e){
e.preventDefault();
if(error_flag && error_required){
$("#ajax-loader").css("display", "block");
$('form#login-form').submit();
}
});
function validateForm(){
var user_pass = document.getElementById('LoginForm[user_pass]').value;
var dob = document.getElementById('LoginForm_dob').value;
var re_pass = document.getElementById('re_pass').value;
var user_name = document.getElementById('LoginForm[user_name]').value;
var email = document.getElementById('LoginForm[email]').value;
var tnc = document.getElementById('checkbox1').checked;
// alert(tnc);
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if(user_name == ''){
validate('LoginForm[user_name]','Nick name is required.');
}else if(email == ''){
removeerror('LoginForm[user_name]');
validate('LoginForm[email]','Email is required.');
}else if(!filter.test(email)){
removeerror('LoginForm[email]');
validate('LoginForm[email]','Please enter valid email.');
}else if(user_pass == ''){
// removeerror('LoginForm[email]');
validate('LoginForm[user_pass]','Password is required.');
}else if(user_pass.length < 6){
removeerror('LoginForm[user_pass]');
validate('LoginForm[user_pass]','Min length should be 6.');
}else if(re_pass == ''){
removeerror('LoginForm[user_pass]');
validate('re_pass','Repeat password is required.');
}else if(user_pass != re_pass){
removeerror('re_pass');
validate('re_pass','Password does not match.');
}else if(dob == ''){
removeerror('re_pass');
validate('LoginForm_dob','Dob is required.');
}else{
if(tnc == false){
document.getElementById('tnc_check').innerHTML = 'Please agree Terms and Condition' ;
document.getElementById("tnc_check").style.color = "red";
error_required = false;
}else{
error_required = true;
document.getElementById("tnc_check").style.display = "none";
removeerror('LoginForm_dob');
}
}
}
function validate(id,msg){
document.getElementById(id).style.border='4px solid red';
document.getElementById(id).value = "";
document.getElementById(id).placeholder = msg;
error_required = false;
}
function removeerror(id){
document.getElementById(id).style.border='none';
error_required = true;
}

Check validation on form submit or button submit event using javascript.
if($('#MyForms').valid())
{
// Do something (Valid)
}
else
{
// Do something (invalid)
}

the answer is simple. put valid in the form post event. all is what you want.
$("#frm").submit(function (e) {
if ($(this).valid()) {
$(".loading").css("display", "inline");
}
});

Related

Unable to redirect to page using window.location

I'm not able to redirect to a single page using windows location in .js page.
However I checked with alert box to see whether the condition is passing true or not and it is working while location is not working.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I feel I'm missing something.
I suspect you're calling validate like this:
<form onsubmit="validate()" ...>
That won't use the return value of validate to cancel the submit. You need a return:
<form onsubmit="return validate()" ...>
Since the submission is not being cancelled, the form submission is a navigation action, which overrides your assignment to window.location.href.
In a comment you've said you're doing this:
<button type="submit" name="submit" onclick="validate()" class="btn-secondary">Sign In</button>
If so, adding the return to the onclick should fix it on any modern browser:
<button type="submit" name="submit" onclick="return validate()" class="btn-secondary">Sign In</button>
But I would move it to an onsubmit on the form instead.
Side note: There's no need for the type="submit" on that button. submit is the default type for button elements.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
}
return false; // ALWAYS return this. else it will proceed with page submit.
}
}

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";
}
});
});

javascript confirm cancel still submits form

I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">
function checkForm(form) {
var frm = document.unsubscribe;
if(!form.captcha.value.match(/^\d{5}$/)) {
alert('Please enter the CAPTCHA digits in the box provided');
form.captcha.focus();
return false;
}
if (validEmail(frm.Email.value) != true) {
alert("Please enter a valid email address");
frm.Email.focus();
return false;
}
if (validEmail(frm.Email.value) == true) {
confirm('Are you sure you want to unsubscribe?');
return true;
}
else {
return false;
}
}
function validEmail(email){
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
status = false;
}
else {
status = true;
}
return status;
}
confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
return confirm('Are you sure you want to unsubscribe?');
}

jQuery: form not submitting with $('#id').submit();, but will submit with a 'submit' button?

I am facing the problem when i submit the form by input type button here is my code :
<form method="POST" id="eulaForm" action="downloadPack.php?packId=<?php echo $_REQUEST['packId'];?>" enctype="multipart/form-data">
that is my form, which looks fine to me. in that form, i put this button:
<input name="declineBtn" id="declineBtn" value="Decline" type="button" class="back">
<script type="text/javascript">
$(document).ready(function(){
$('#declineBtn').click( function() {
searchTxt = $('#searchText').val();
// ajax logic to test for what you want
if (searchText != '') { return chgAction(searchTxt); } else { return true;}
});
});
function chgAction(cmpText)
{
if(cmpText != '')
{
$('#eulaForm').attr('action', 'searchResult.php');
alert("After - action = "+$("#eulaForm").attr("action"));
//submit the form
$('#eulaForm').submit();
}
else{
url = '<?php
echo basename($_SERVER['HTTP_REFERER']);?>';
window.parent.location.href = url;
//parent.history.back();
return false;
}
}
</script>
and as you can see, it calls $('#eulaForm').submit(); , but the form is not submitting (ie. the page is not refreshing). why is that?
thanks!
try like this:
wrap up chgAction() inside document ready and add preventDefault()
$(document).ready(function(){
$('#declineBtn').click( function(e) {
e.preventDefault();
searchTxt = $('#searchText').val();
// ajax logic to test for what you want
if (searchText != '') { return chgAction(searchTxt); }
else { return true;}
});
function chgAction(cmpText)
{
if(cmpText != '')
{
$('#eulaForm').attr('action', 'searchResult.php');
alert("After - action = "+$("#eulaForm").attr("action"));
//submit the form
$('#eulaForm').submit();
return false;
}
else{
url = '<?php
echo basename($_SERVER['HTTP_REFERER']);?>';
window.parent.location.href = url;
//parent.history.back();
return false;
}
}
});

Javascript validation of login form - field must be not blank and contain a "\"

Here is the code I have now.
function ns_check()
{
var login = document.forms['vpnForm'].login.value;
var passwd = document.forms['vpnForm'].passwd.value;
var domainname = login.indexOf("\\")
if (domainname = - 1){
window.alert(_("You need to enter a domain name")); return false;
}
if (login == ""){
window.alert(_("You need to enter login name")); return false;
}
if (passwd == ""){
window.alert(_("You need to enter passwd")); return false;
}
return true;
}
When you do not use a backslash in the login box it does popup an alert window, but it is empty.
Any help would be appreciated.
if (domainname = - 1)
should be
if (domainname === - 1)

Categories