I need help on js and jquery form validation - javascript

i have problem with this query when i fill my email box with correct email it can validate and then ask me correct email and when i change my email box to empty it shows me correct email address. let check this http://www.icodecrew.com/register
if(email == "") {
$("span.val_email").html("Please Enter Your Correct Email-ID.").addClass('validate');
validation_holder = 1;
} else {
if(!email_regex.test(email)){ // if invalid email
$("span.val_email").html("Invalid Email!").addClass('validate');
validation_holder = 1;
} else {
$("span.val_email").html("");
$(document).ready(function(){
$("#email").change(function(){
$("span.val_email").html("<img src='spinner.gif' /> Please wait until we check...");
var email=$("#email").val();
$.ajax({
type:"POST",
url:"includes/checkemail.php",
data:"email="+email,
success:function(data){
if(data==0){
$("span.val_email").html("<img src='accept.png' title='available' />");
}
else{
$("span.val_email").html("<img src='error.png' /> E-Mail is Already registered");
}
}
});
});
});
}
}

As mentioned by #PlantTheldea in the comments to your question, your order of operations is severely broken. Having read through your code, this is the closest I can come to what I believe you want. It is UNTESTED and serves only to help you determine the order in which your steps should be executed:
$(function () {
var email_input = $('#email');
email_input.change(function () {
var status_display = $('span.val_email'),
email = email_input.val();
if (email === '') {
status_display
.html('Please Enter Your Correct Email-ID.')
.addClass('validate');
validation_holder = 1;
} else {
if (!email_regex.test(email)) {
status_display
.html('Invalid Email!')
.addClass('validate');
validation_holder = 1;
} else {
status_display
.html('<img src="spinner.gif" /> Please wait until we check...')
.removeClass('validate');
$.ajax({
type: 'POST',
url: 'includes/checkemail.php',
data: {
email: email
},
success: function (data) {
if (data == 0){
status_display.html('<img src="accept.png" title="available" />');
} else {
status_display.html('<img src="error.png" /> E-Mail is Already registered');
}
}
});
}
}
});
});

Related

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

how to start another fuction in java script and ajax

I want to call another function after an ajax function finishes. After successful registration of a user, I want to have a callback function, but when I try, my sign up function stops working:
function signUp(){
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
}
EDIT your $(document).ready(function().. shouldn't be inside another function, because this way it will only get called when that function is called, and problably that is not what you intended, as i don't know how you use signUp() function i can't really tell.
You can use this way of making ajax request
function signUp(){
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.ajax({
type: "POST",
url: "http://localhost:5000/your/endpoint",
data: {
name1: name,
email1: email,
password1: password
},
success: function (data, status, xhr) {
// function called when it has succeeded
// Do what you want here in case of success
// The best way to do this should be used with statusCode because basically you
// only want to know that your post was OK.
},
statusCode: {
// Add more status code if you want to do something for each
200: function(){
$("form")[0].reset();
alert('You have Successfully Registered.....');
},
500: function(){
// In case of server error you should do something also
}
}
error: function(xhr, msg, err){
// Function called when error happens
}
})
}
});
});
}
You can even define functions to be called when a given status code is given as response, you can find the complete reference on http://api.jquery.com/jquery.ajax/

Message about sent is not working

I have code that checks whether the address is ok and sends it. After sending the information appears that the message was sent.
When I give the wrong email address format - appears the message.
Then when I give the correct address - the message you sent is not working.
What is wrong?
jQuery code:
<script type="text/javascript">
{literal}
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
{/literal}
$(document).ready(function() {
$('#mybtn').click(function() {
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
//e.preventDefault();
}
if (validateEmail(sEmail)) {
$('#contact').submit(function() {
$.ajax({
url : '/contact/process',
data : $('#contact').serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
return false;
});
}
else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
</script>
<script type="text/javascript">
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
$(document).ready(function() {
$('#contact').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : '/contact/process',
data : $(this).serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
});
$('#mybtn').on('click', function(e) {
e.preventDefault();
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
}
if (validateEmail(sEmail)) {
$('#contact').trigger('submit');
} else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
Try this way, first set listener on your contact form, second listen for event on "send button"
If it's "simple form" you could just put everything in on('submit') listener
Fiddle

JavaScript/Jquery best practice

I've made a few functions to check form input for an ajax request. I am still getting use to JavaScript and some of these ajax requests. I am looking for any suggestions to better work with JavaScript functions, and passing variables through a function level scoping. Thank You in Advance!
Code Works as of now!
Edited!
//Form Handler
$("#form-submit").submit(function(e) {
e.preventDefault();
$.ajax({
beforeSend: function(){
return (checkAll());
return (passwordCheck());
},
complete: function(){
},
type: "POST",
url: '',
data: $("#form-submit").serialize(),
success: function(data)
{
// Set Session Php Etc
alert('php ran');
return true;
}
});
});
//Pushing all Input Values to an Array
function checkAll() {
var arr = [];
$('#form-submit :input').each(function() {
arr.push($(this).val());
});
return (checkArray(arr));
}
//Checks Array for empty strings
function checkArray(arr){
for(var i=0; i < arr.length; i++) {
console.log(arr[i]);
if (arr[i].trim() == '') {
alert('Please Enter All Fields');
return false;
} else {
return true;
}
}
}
//Matches Password
function passwordCheck() {
var pass1 = $('#password').val();
var pass2 = $('#password-check').val();
if(pass1 != pass2) {
$('#password').addClass('highlight');
$('#password-check').addClass('highlight');
alert("Passwords don't match");
return false;
} else {
$('#password').removeClass('highlight');
$('#password-check').removeClass('highlight');
return true;
}
}

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Categories

Resources