Prevent user to send empty fields - javascript

My jQuery validation form warns user if he tries to send empty data if he clicks "Next" button.
Anyway, user still able to send empty data by pressing Enter.
So I used code below, it makes pressing Enter same with clicking "Next" button;
// this script makes pressing Enter gives error. But empty data still goes to database.
$('.form-horizontal').keypress(function (event) {
if (event.which === 13) {
$(".next").trigger('click');
}
});
This code only prevents user to go next step. But when user hits the Enter data being written to database even though he sees "Error Message".
*
Well, server-side verification prevents that easily. But why it's necessary keep server busy with that if we can prevent earlier?
Here is JsFiddle you can test the whole thing:
http://jsfiddle.net/6zu2vsj7/3/
*
Is there any way to make it work without keeping servers busy with empty fields? And I don't want to prevent user pressing Enter because this is not cool at all and not good for user experience.

You can add a condition to check whether the form is valid or not before you sending the data to server as below. hope this helps...
// Let's act like we send to database.
$(function(){
$('input[type=submit]').click(function(){
if($("#myform").valid()){
$.ajax({
type: "POST",
url: "sent.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#stepsuccess').html('Sent to the database. Strange.');
},
success: function(data){
$('#stepsuccess').html(data);
}
});
}
});
});

You just need to prevent the default behavior for that event
you can use this
$('.form-horizontal').keypress(function (event) {
if (event.which === 13) {
event.preventDefault();
$(".next").trigger('click');
}
});

Try this:
$(".form-horizontal").submit(function(e){
//do somethings or other validations
return false;
});
well! server side validation is necessary because client side validation is just for normal users! not hackers and robots! got it?!
in fact client side validation can be easily pass.

Related

Page redirect in jQuery fails randomly. Race condition?

Elaborating on an example from the very good post by Felix Kling I wrote some jQuery code to authenticate a user. If the authentication is successful the window.location object should be assigned/replaced to a new URL.
The redirection occasionally fails, even though the user is authenticated correctly: based on the values of sessionStorage('Auth') the looks of the menus for an authenticated user are modified by some other JS code, so I know when the credentials were entered correctly.
Here is my code.
$(document).ready(function() {
$('#submit').click(function() {
var webServiceHref = window.location.href;
var webServicePath = webServiceHref.slice(0,webServiceHref.lastIndexOf("/"));
var serviceUrl = webServicePath + "/login.php";
$.post(serviceUrl,
{
Email: $("#Email").val(),
Password: $("#Password").val()
}).done(function(data, status) {
var json = JSON.parse(data);
if (json.valid == true){
sessionStorage.setItem('Auth', true);
sessionStorage.setItem('FirstName', json.FirstName);
sessionStorage.setItem('Email', json.Email);
$("#messageLine").val("Authentication succeded");
$(location).attr('href', webServicePath + "/welcome.html");
// window.location.href = webServicePath + "/welcome.html";
} else {
sessionStorage.clear();
$("#messageLine").val("Incorrect Username or Password");
}
});
}); // click
}); // ready
This behavior does not depend from the way the redirection is called:
I left in my code, commented out, some of the JS and jQuery
combinations of methods (window.location.assign, window.location.replace etc.) suggested in numerous posts on SO.
I have even tried .reload() without success.
In Chrome inspector I can even see the callback statements being executed, the assignment of the new URL being made, but when the function returns the window object sometimes does not change, and sometimes ... it does.
Perhaps the assignment of the URL is queued after other event which causes the original login.html page to be reloaded?
What am I missing? Am I using the deferred object incorrectly?
Thank you in advance for your help.
If your "#submit" element is actually submitting a form (e.g. it is an input of type "submit" within a form), that could cancel the page redirection. E.g. when no action is specified on the form, it just reloads the same page, preventing your modification of window.location.href from having any effect.
See also that post: javascript redirect not working anyway
You have 3 easy possible solutions:
Turn your element/button into a normal one (not a submit).
Prevent the element/button from submitting the form (function (event) { event.preventDefault(); /* rest of your code */}).
Attach your main callback on the form submit event. The user is then able to trigger the action by hitting "Enter", not just by clicking on the submit button.

JS/JQuery/PHP - How to echo errors on form validate failure, and jump to div on success?

I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.

Checking for duplicate username

I am doing a registration page, for my mobile app, and want to check for duplicate usernames entered by the user/client
I have a button on the page that when clicked, checks availability of the username. However I would like to also incorporate that automatically, if not already done so, when the client clicks submit/go to step 3,
I want to perform the check for duplicate usernames using Ajax and if there exists a duplicate, then refresh the SAME page with the error message for duplication, else proceed to step 3.
In my HTML file I have some js that does the following:
$("#check-username").click(function() {
(...this works as I am able to click the CHECK button
and see if the username exists)
I have another js file, that is sourced in my HTML that does the following:
submitHandler : function() {
$("#reg1").hide();
$("span#step").html("2");
$("#check-username").click;
$("#reg3").show();
scrollTop();
}
When I click on Go to next step which is reg3, It does not do the validation for check-username. Is my method/syntax for calling check-username correct?
$("#check-username").click;
^^----- Missing Braces
supposed to be
$("#check-username").click();
The problem is you need to go to step 3 only after the validation ajax request returns from the server. You also are going to need to look at the response from the server to see if it's a duplicate. For example:
$("#check-username").click(function() {
validateUser();
});
function validateUser(){
return $.ajax({
url: '/path/to/validate'
});
}
And your submit handler stuff:
submitHandler : function() {
$("#reg1").hide();
$("span#step").html("2");
validateUser()
.done(function(r){
//for example...
if(r.isValidUser){
$("#reg3").show();
scrollTop();
}
});
}

MVC 3: running javascript after validation has completed but before the actual post?

Folks,
I have an MVC3 data entry form scenario that involves asking the user to confirm something after client-side validation has been satisfied, but before the post to the server.
Is there a way to insert some javascript into the sequence of events after the validation framework gives the go-ahead to post back, but before the post back happens?
(And of course if the user declines the confirmation, the post back has to cancel, too. )
Many thanks.
You could subscribe for the .submit event of the corresponding form and check if it is valid:
$(function() {
$('form').submit(function() {
if ($(this).valid()) {
// client validation passed successfully
} else {
alert('there was an error during client validation');
// cancel the submission of the form
return false;
}
});
});
or if you don't want to subscribe for the submission of the form and you want to verify if client validation passes for a given form you could always check like this:
var isValid = $('#someFormId').valid();

Validating and Submitting a form using Javascript + Ajax

Here's what I'm trying to do.
When the 'Submit' form is clicked on my form, a javascript function will loop through all the fields of the form.
For each field a function will be called which would return true/false to indicate if it was filled in correctly or not.
If a false is returned, it shows an error message next to that field.
If all fields are correct, it submits the form. If not, it doesn't submit.
Here's the tricky part. While most of the validation is being done via javascript, the username and email need to be validated via ajax to see if the username/email is already in use or not.
The structure i'm currently using for this ajax function is something similar to this:
function validateSomething()
{
var valid;
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
return valid/
}
But that currently doesn't work.
What can I do to make it work, i.e can I stop the validateSomething() function from returning a value until its set to true/false by the inner function?
Would something like this work:
function validateSomething()
{
var valid="unset";
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
//Loop without returning until valid is set to true or false
while (valid=='unset')
{
//Do nothing?
}
return valid/
}
You can force the ajax-call to wait with async: false.
Like this using jquery:
function validateSomething() {
var valid;
$.ajax({
url: "something.php",
data: {x: y},
type: "GET",
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
valid= response.valid;
}
});
return valid;
}
However, the big win when using AJAX is that it is asynchronous. This synchronous call might lock up the browser while it is waiting for the server.
You probably don't want to. (Or more appropriately, "Go for it, but be careful when doing so.")
Validating via AJAX is hip and slick and awesome. But it is -not- a substitute for validating server-side. And AJAx validation is -not- server-side validation. I can take the return of your function that says false and flip it to true and submit the form happily, even though you checked to make sure the username wasn't taken 'on the server'. Javascript runs on the client and can't be trusted.
Any validation you do via an AJAX call must be re-done on the server when you actually submit the form.
If you do that, then yea, AJAX validation is, again, hip and slick and awesome. So go for it. To submit a form using javascript (e.g. in the AJAX call-back handler function) you would say:
if(formwasValid)
{
document.getElementById('idOfForm').submit();
$('#idOfForm').submit(); //jQuery
}
else
{
alert('Invalid text');
}
I stopped doing extensive form validation on the client side as the code has to be duplicated on the server side anyway.
On the client-side, I just do some basic syntax checking of fields via regular expressions. These checks will be immediately triggered when the user starts typing, but they just give a visual notice as to when something went wrong (red border, different background color, a red 'X' next to the field...).
I don't prevent the user from submitting even invalid forms: Then, the server-side code with it's more detailed checks gets to work, which can easily restructure the form to separate valid from invalid fields and generate in-depth explanations as to why a check failed.

Categories