IF/ELSE on Javascript works strangely - javascript

I have a form where I ask for an email that I validate trought a regular expression, if the email is correct, I do a submit, if not I send an alert.
When I put an invalid email the alert is shown, but if I put a valid email the alert is shown and then the submit() is done, I don't even know how is this posible! Here is my code.
$('#sinCopago').on('click', function(event){
if($('#nombreContratante').val() != "" && $('#motivo').val() != ""){
if($('#fechaNac').val() > hoy){
alert("Ingresa una fecha de nacimiento válida.");
}else{
if(validarMail($("#correo")) == true){
event.preventDefault();
$('#progressBarSisnova').modal({show:true});
$('#payment-form-Sisnova').submit();
}
else{
alert("Ingresa un correo válido");
}
}
}
else{
alert("Por favor llene todos los campos");
}
});
function validarMail(email){
var caract = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if(caract.test(email) == false){
return false;
}
else{
return true;
}
}

You're currently passing the $("#correo") jQuery object to validarMail:
if(validarMail($("#correo")) == true){
and proceed to test that object:
if(caract.test(email) == false){
Which won't work, of course, because you're not testing a string. Try passing the .val() of #correo instead. so that the eventual .test( is called with the value string, not the jQuery object:
if(validarMail($("#correo").val()) == true){
Feel free to remove the == true part, validarMail already returns a boolean:
if(validarMail($("#correo").val())){
You should also preventDefault when the test fails, not when the test succeeds - that way, the form will be submitted as normal without interruption only when the test succeeds. The code will also probably be flatter and easier to read if you return when there's an error:
$('#sinCopago').on('click', function(event){
if($('#nombreContratante').val() === "" || $('#motivo').val() === "") {
event.preventDefault();
return alert("Por favor llene todos los campos");
}
if($('#fechaNac').val() <= hoy){
event.preventDefault();
return alert("Ingresa una fecha de nacimiento válida.");
}
if(!validarMail($("#correo").val())){
event.preventDefault();
return alert("Ingresa un correo válido");
}
$('#progressBarSisnova').modal({show:true});
$('#payment-form-Sisnova').submit();
});
If clicking #sinCopago submits the form without preventDefault, then there's no need for the final line there $('#payment-form-Sisnova').submit();. (Otherwise, then there may be no need for preventDefault at all, if the event's default action doesn't cause a form submission or other undesirable behavior)

you should pass the value of field for function validarMail(), so replace the current cod
if(validarMail($("#correo")) == true)
for
if(validarMail($("#correo").val()) == true)
an you can improve you function.
function validarMail(email){
var caract = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
return caract.test(email)
}

Related

JavaScript validation code

I am using JavaScript to validate some form fields. My question is about the code inside
$("#alias").keyup(function(){
This is my script for the validation:
<script type="text/javascript">
$(document).ready(function(){
console.log("principio");
// Setup the ajax indicator
// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){
$('#ajaxBusy').show();
}).ajaxStop(function(){
$('#ajaxBusy').hide();
});
//control de alias
$("#alias").keyup(function(){
var ID=$("#alias").val();
var REST=$("#rest").val();
var ACTUAL = "<?php echo $row_Recordset1['alias_mesero']?>";
$.post("check_username_edit.php", { username: ID, rest: REST, actual: ACTUAL},
function(result){
console.log(result);
//if the result is 1
if(result == 1){
document.getElementById('mensajealias').innerHTML ="Nombre corto disponible";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 2){
document.getElementById('mensajealias').innerHTML ="No ha modificado el nombre corto";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 0){
document.getElementById('mensajealias').innerHTML ="Nombre corto no disponible, ya existe";
document.getElementById('boton').style.visibility='hidden'; // hide
document.getElementById('mensajeboton').innerHTML ="No se puede insertar hasta que no modifique los datos";
}
});
});
//control de rest
$("#rest").change(function(){
var ID=$("#alias").val();
var REST=$("#rest").val();
var ACTUAL = "<?php echo $row_Recordset1['alias_mesero']?>";
$.post("check_username_edit.php", { username: ID, rest: REST, actual: ACTUAL},
function(result){
console.log(result);
//if the result is 1
if(result == 1){
document.getElementById('mensajealias').innerHTML ="Nombre corto disponible";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 2){
document.getElementById('mensajealias').innerHTML ="No ha modificado el nombre corto";
document.getElementById('boton').style.visibility='visible'; // hide
document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";
}
else if(result == 0){
document.getElementById('mensajealias').innerHTML ="Nombre corto no disponible, ya existe";
document.getElementById('boton').style.visibility='hidden'; // hide
document.getElementById('mensajeboton').innerHTML ="No se puede insertar hasta que no modifique los datos";
}
});
});
});
</script>
If the user enters the text character by character, the validation takes place like a charm.
But I have detected that if the user enters the text very quickly, then sometimes the validation doesn't return the right value.
I guess I could use change(function) instead of keyup(function), but I would prefer that the user doesn't have to leave the field to be validated.
Any advice is welcome.
I have used this approach on a search box that I only wanted to execute the search when the user stopped typing for a short period of time:
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$("#alias").on('propertychange keyup input paste', function () {
delay(function () {
//validate
}, 1000);
});
It starts a timer for 1 second when any of those events fire and only executes the validation if the timer expires. If any new events are received the timer is reset to 1 second. This event handler also works for cutting and pasting from/to the input.
Two points for you to consider:
1) Old style Keyup keydown events are not reliable. You always need backup validation from the backend if you use them. If the user inputs quickly, few keyup events will be fired but you are not even sure which event first.
2)Morden Browsers support new events like "input", if possible you should use new events.

prevent button form from submission Javascript

This form keeps on submitting even if it executes the return value, what is the problem with my code?
function formhash (form, password)
{
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("cpassword").value;
var ok = true;
if (password != cpassword) {
//alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("cpassword").style.borderColor = "#E34234";
ok = false;
return;
}
else
{
$.post('insert_home.php'
{PRIMAID:PRIMAID,EDITCAP:EDITCAP,EDITIMG:EDITIMG,EB_TITLE:EB_TITLE}).done(function(data){
alert ("Book Successfully Updated");
location.reload();
});
var p = document.createElement("input");
form.appendChild(p);
p.name="p";
p.type="hidden";
p.value=hex_sha512(password.value);
password.value="";
form.submit();
}
}
You are calling form.submit();, remove it and it won't submit.
You are using the wrong variable names "password" and cpassword". You created pass1 and pass2 so you need to use those.
Change to this:
//You were using the WRONG variable names
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("cpassword").style.borderColor = "#E34234";
ok = false;
return false;
}
I don't see where formhash() is used.
The code calls the submit, not the function.
If it submits the form, it' because it's falling in the else condition.
Add lots of "console.log("debug_X")" where "X" is a number different each time.
You have to add inside a console.log the value of pass1 and pass2.
Maybe you are passign a value instead of an object or maybe the reversed situation can happen also.
My instinct tells me to check both password object, and their values.
Also it tells me that you didn't check the content of pass1 and pass2 before posting a comment to Don Rhummy.
Check carefully and please search more before posting your next answer.
You can have the value by doing "console.log(pass1);" and by opening firebug and by checking the javascript console.
Remove Action attribute from Form.

If Statement Not Acting As Expected

$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.

AJAX stored requests and form submitting

I am working on a jQuery validation "plugin" (not yet a plugin) that use my Zend_Form validators to verify the fields before submitting, client-side, so I only have to specify my constraints one time instead of two (Zend Validators + jQuery Validate Plugin, for example).
I store the validation AJAX requests for each field, then wait for them to finish, and then read the results and show or not an error message.
The problem : when I enter validated strings and hit submit, it shows no errors (good so far), but I have to re-click the submit button the form to really submit it.
Making a return true or false inside the .whenAll function is ignored and does not work, that's why I used a flag to tell the function if yes or no it can really submit the form.
$(function() {
var form = $('form'); // target form
var requests = [], validations = []; // used to store async requests and their results
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs we want to check in the form
var cancelSubmit = true; // skip validation flag
form.submit(function( ) {
// if we call the submit inside the function, skip validation and do submit the form
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
this.submit();
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations
requests.length = 0;
validations.length = 0;
// for each input (text/password), storing the validation request
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
// response is formatted like this
// { valid: 1 } or { valid: 0, message:"This is the error message" }
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error and store result
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
validations.push(0);
}
// else, remove error (if there was) and store the result
else if(json.valid == 1) {
if($(formGroup).hasClass('has-error'))
{
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
}
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
// and if no error ("0") in the results, we resubmit the form with skip-flag
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.off('submit');
form.submit();
}
else
console.log('[-] There is still errors.');
}
});
});
});
// there are errors, so we won't submit the form
if(cancelSubmit === true)
return false;
});
});
Do you see a logic flaw in my code ? Maybe re-submitting the form with a flag isn't the right way to do it ?
You're returning from a sub scope rather than from the form submit handler. Instead, always prevent the submit, and then force it to submit with form[0].submit() when you want it to submit.
form.submit(function(e) {
e.preventDefault();
...
// now i want to submit...
form[0].submit();
form[0].submit() will bypass your jquery bound submit handler.

JavaScript form validation with a shake effect

I have some JavaScript form validation I'm using before I send it across to my PHP. (I'm still learning). but my question for you today is how I would get my error message to shake without reloading the page. My below JS code seems to reload the page when I click submit. The error message style is set to disply:none; by default and only shows when needed.
I hope you understand what I am getting at. ha ha Thank you in advance.
Here's the js code.
function validateLoginForm() {
var x = document.getElementById('email').value;
if (x == null || x == "" || x == "Email") {
document.getElementById('errorWrapper').style.display='block';
document.getElementById('errorText').innerHTML='Please enter your Email address!';
shakeIt();
return false;
}
}
and the jQuery.
$(document).ready(function() {
function shakeIt(){
$('#errorWrapper').effect("shake", { times:5, distance:8 }, 50);
}
});
You need to do it on form.submit ie
$('#loginForm').submit(function(e){
var x= $('#email').val();
if (x==null || x=="" || x=="Email")
{
$('#errorWrapper').show();
$('#errorText').text('Please enter your Email address!');
e.preventDefault();
shakeIt();
}
return true;
});
Returning false will make the page not reload..

Categories

Resources