validating This form (numbers only)? - javascript

Background##
i am a complete noob with JS (i can slightly read it, but cant write it)
Problem
Link: http://s328792954.websitehome.co.uk//multi_step_form/
Im trying to make a multi-step form,
and i cam across a tutorial on-line which showed a basic example.
anyway.....
i've added a field for number only (example:loan amount)
but the coding i use is obviously wrong because now it will not accept any form of input
+ i think its interfering with the other coding.
the section starting with '//check if amount input is numbers' is the problem
Copy code
$(function(){
//original field values
var field_values = {
//id : value
'username' : 'username',
'password' : 'password',
'cpassword' : 'password',
'firstname' : 'first name',
'lastname' : 'last name',
'email' : 'email address',
'amountborrow' : '000'
};
//inputfocus
$('input#username').inputfocus({ value: field_values['username'] });
$('input#password').inputfocus({ value: field_values['password'] });
$('input#cpassword').inputfocus({ value: field_values['cpassword'] });
$('input#lastname').inputfocus({ value: field_values['lastname'] });
$('input#firstname').inputfocus({ value: field_values['firstname'] });
$('input#email').inputfocus({ value: field_values['email'] });
$('input#amountborrow').inputfocus({ value: field_values['amountborrow'] });
//reset progress bar
$('#progress').css('width','0');
$('#progress_text').html('0% Complete');
//first_step
$('form').submit(function(){ return false; });
$('#submit_first').click(function(){
//remove classes
$('#first_step input').removeClass('error').removeClass('valid');
//check if amount input is numbers
var fields = $('#first_step input[type=amountborrow]');
var numOnly = /^[0-9]$/;
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='amountborrow' && !numOnly(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
//check if inputs aren't empty
var fields = $('#first_step input[type=password]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
if( $('#password').val() != $('#cpassword').val() ) {
$('#first_step input[type=password]').each(function(){
$(this).removeClass('valid').addClass('error');
$(this).effect("shake", { times:3 }, 50);
});
return false;
} else {
//update progress bar
$('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
//slide steps
$('#first_step').slideUp();
$('#second_step').slideDown();
}
} else return false;
});
$('#submit_second').click(function(){
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#third_step').slideDown();
} else return false;
});
$('#submit_third').click(function(){
//update progress bar
$('#progress_text').html('100% Complete');
$('#progress').css('width','339px');
//prepare the fourth step
var fields = new Array(
$('#username').val(),
$('#password').val(),
$('#email').val(),
$('#firstname').val() + ' ' + $('#lastname').val(),
$('#age').val(),
$('#gender').val(),
$('#country').val(),
$('#amountborrow').val()
);
var tr = $('#fourth_step tr');
tr.each(function(){
//alert( fields[$(this).index()] )
$(this).children('td:nth-child(2)').html(fields[$(this).index()]);
});
//slide steps
$('#third_step').slideUp();
$('#fourth_step').slideDown();
});
$('#submit_fourth').click(function(){
//send information to server
alert('Data sent');
});
});
please help
(sorry if this is wrong section i didnt really understand forum sections)
#edit#
#Banaan information was great :) THANKS!
but the form still accepts the incorrect info...
the 'field' doesnt but the form does and proceeds to the next step.
Do i need a }else return false somewhere?
//first_step
$('form').submit(function(){ return false; });
$('#submit_first').click(function(){
//remove classes
$('#first_step input').removeClass('error').removeClass('valid');
//check if amount input is numbers
var fields = $('#first_step input[type=amountborrow]');
var numOnly = /^[0-9]+$/;
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<3 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='amountborrow' && !numOnly.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
} else {
$(this).addClass('valid');
}
});
//check if inputs aren't empty
var fields = $('#first_step input[type=password]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
if( $('#password').val() != $('#cpassword').val() ) {
$('#first_step input[type=password]').each(function(){
$(this).removeClass('valid').addClass('error');
$(this).effect("shake", { times:3 }, 50);
});
return false;
} else {
//update progress bar
$('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
//slide steps
$('#first_step').slideUp();
$('#second_step').slideDown();
}
} else return false;
});
Pleas further Advise

You created some sort of a new RegExp object, which is the right direction, except you probably want to accept any number instead of only a single digit:
var numOnly = /^[0-9]+$/;
In which [0-9] means a digit, and + means one or more occurrences.
The way in which you use that RegExp object, however, is incorrect. if you look at the e-mail regular expression in the second step, they use
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var value = $(this).val();
emailPattern.test(value)
The emailPattern.test(value) part is what you missed. To check if the input is a number, you use not !numOnly(value) but !numOnly.test(value).
For a more complete tutorial on javascript regular expressions, you might want to take a look at W3Schools

Related

How to execute a JS function if the parameters do not match?

I took this code from internet to modify, to practice JS, though I fail to call the function when the input length is equal 0. So basically I click on the "Add a column" and it opens the console to give the name of the column you want to make, though when the input length as I said is equal to 0, it raises and alert, but it doesn't ask again for the input (I don't know how to call the function so the input console will show up again).
Down below you have the JS code, for the whole code (html, css, js) click here.
function Column(name) {
if (name.length > 0) {
var self = this; // useful for nested functions
this.id = randomString();
this.name = name;
this.$element = createColumn();
function createColumn() {
var $column = $("<div>").addClass("column");
var $columnTitle = $("<h2>")
.addClass("column-title")
.text(self.name);
var $columnCardList = $("<ul>").addClass("column-card-list");
var $columnDelete = $("<button>")
.addClass("btn-delete")
.text("x");
var $columnAddCard = $("<button>")
.addClass("add-card")
.text("Add a card");
$columnDelete.click(function() {
self.removeColumn();
});
$columnAddCard.click(function(event) {
self.addCard(new Card(prompt("Enter the name of the card")));
});
$column
.append($columnTitle)
.append($columnDelete)
.append($columnAddCard)
.append($columnCardList);
return $column;
}
} else if (name.length == 0) {
alert("please type something");
} else {
return;
}
}
Column.prototype = {
addCard: function(card) {
this.$element.children("ul").append(card.$element);
},
removeColumn: function() {
this.$element.remove();
}
};
function Card(description) {
var self = this;
this.id = randomString();
this.description = description;
this.$element = createCard();
function createCard() {
var $card = $("<li>").addClass("card");
var $cardDescription = $("<p>")
.addClass("card-description")
.text(self.description);
var $cardDelete = $("<button>")
.addClass("btn-delete")
.text("x");
$cardDelete.click(function() {
self.removeCard();
});
$card.append($cardDelete).append($cardDescription);
return $card;
}
}
Card.prototype = {
removeCard: function() {
this.$element.remove();
}
};
var board = {
name: "Kanban Board",
addColumn: function(column) {
this.$element.append(column.$element);
initSortable();
},
$element: $("#board .column-container")
};
function initSortable() {
$(".column-card-list")
.sortable({
connectWith: ".column-card-list",
placeholder: "card-placeholder"
})
.disableSelection();
}
$(".create-column").click(function() {
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);
});
// ADDING CARDS TO COLUMNS
todoColumn.addCard(card1);
doingColumn.addCard(card2);
});
After the line:
alert("please type something");
Add the following:
$(".create-column").click();
That programmatically "clicks" the Create Column button.
If you want to prompt the user to enter column name if length is 0, just add this lines of code to your if-stament:
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);.
As shown below:
else if (name.length == 0) {
alert("please type something");
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);
} else {
return;
}
If that was your question, this should be able to fix it.

How do I stop Javascript form validate submitting before json response has returned?

I have an html form that is validated by Javascript, but since connecting to an external API the form submits before the API queries have returned
All of the alerts are triggering correctly, however the last line of code - if (rtn) {
$('#saleForm')[0].submit();
} -
is resolving before the api call data returns and therefore once I accept the alerts the form always submits (as rtn is always true).
I am using setTimeout to wait for the return in the two if() blocks, and have tried a do/whilst loop around submit but that didn't work.
Is there a method I can use to force the submit to wait until all the previous conditions have been checked, before if(rtn)?
$('#saleForm').off('submit').on('submit', function(e) {
e.stopPropagation();
e.preventDefault();
var rtn = true;
if (window.hasIntegration == 'no' && $('#eventDate').val() == '') {
alert('Please choose the event date and time.');
$('#eventDate').focus();
return false;
}
$('.itemValue').each(function() {
if ($(this).val() == '') {
alert('Please ensure all values are entered.');
$('#ticket-rows').focus();
rtn = false;
}
});
if (!$('#terms').is(':checked')) {
alert('Please accept the terms and conditions.');
return false;
}
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
});
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
}, 1000);
}
if (rtn) {
$('#saleForm')[0].submit();
}
});
Thanks everybody! I have brought the submit function inside the setTimeout function, and then brought that whole block inside the $.get api call as per #Gendarme. I've also added else after the if integration == 2, to make the submit work if no integration exists. New code below. Works a treat now.
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
if (rtn) {
$('#saleForm')[0].submit();
}
}, 1000);
});
} else {
if (rtn) {
$('#saleForm')[0].submit();
}
}
});

how to convert functions into a JQuery plugin

I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()

Reverse RegEx for URL detection

I'm using the following regex:
/((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\#)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\#\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$)/gi
In a form that requires the visitor to enter their url.
It works but, for my textarea (msg),
I'd like the reverse effect.
Here is the JQ I use:
$.fn.goValidate = function() {
var $form = this,
$inputs = $form.find('input:text, input:password, textarea');
var validators = {
name: {
regex: /^[A-Za-z]{3,}$/
},
pass: {
regex: /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/
},
email: {
regex: /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/
},
phone: {
regex: /^[2-9]\d{2}-\d{3}-\d{4}$/
},
website: {
regex: /((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\#)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\#\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$)/gi
},
msg: {
regex: ????????????????????????????
},
};
var validate = function(klass, value) {
var isValid = true,
error = '';
if (!value && /required/.test(klass)) {
error = 'This field is required';
isValid = false;
} else {
klass = klass.split(/\s/);
$.each(klass, function(i, k){
if (validators[k]) {
if (value && !validators[k].regex.test(value)) {
isValid = false;
error = validators[k].error;
}
}
});
}
return {
isValid: isValid,
error: error
}
};
var showError = function($input) {
var klass = $input.attr('class'),
value = $input.val(),
test = validate(klass, value);
$input.removeClass('invalid');
$('#form-error').addClass('hide');
if (!test.isValid) {
$input.addClass('invalid');
if(typeof $input.data("shown") == "undefined" || $input.data("shown") == false){
$input.popover('show');
}
}
else {
$input.popover('hide');
}
};
$inputs.keyup(function() {
showError($(this));
});
$inputs.on('shown.bs.popover', function () {
$(this).data("shown",true);
});
$inputs.on('hidden.bs.popover', function () {
$(this).data("shown",false);
});
$form.submit(function(e) {
$inputs.each(function() { /* test each input */
if ($(this).is('.required') || $(this).hasClass('invalid')) {
showError($(this));
}
});
if ($form.find('input.invalid').length) { /* form is not valid */
e.preventDefault();
$('#form-error').toggleClass('hide');
}
});
return this;
};
My form now shows a popup when the user does not enter a proper URL (co.uk / co.jp etc. excluded... it's regex xD)
But for my textarea, I would like to show a popup when they DO enter a URL (the reverse)
How is this done? Thanks a LOT in advance!
leave the NOT operator ! off of the regex test
if(value && validators["website"].regex.test(value)){
alert("Value has a url");
}
Thanks to #kei
First, check if input contains URL
/((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\#)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\#\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$)/gi
Second, check if input does NOT contain URL
/^(?!((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\#)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\#\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$))/gi

AJAX form submission issue

Following code are HTML markup and JS part of my signup page. I don't know what's wrong but, when I left all text inputs unfilled and click on submit button for the first time, it validates and gives error message. But when click second time it directly posts all data to php file. Please take a look at my js file (P.S. Don't pay attention to validation error messages:))
HTML markup looks like that
<form id="signup_form" action="core/code/PHP/registration/signup.php" method="post">
...
</form>
And js part
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/,
fname, mname, lname, email, pass, confirm_pass;
/*VALIDATION*/
/*check if input fields empty or not*/
function vPass1() {
var isValid = true;
if (!fname) {
$("#fname").attr('class', 'invalid');
isValid = false;
}
if (!lname) {
$("#lname").attr('class', 'invalid');
isValid = false;
}
if (!mname) {
$("#mname").attr('class', 'invalid');
isValid = false;
}
if (!email) {
$("#email").attr('class', 'invalid');
isValid = false;
}
if (!pass) {
$("#pass").attr('class', 'invalid');
isValid = false;
}
if (!confirm_pass) {
$("#confirm_pass").attr('class', 'invalid');
isValid = false;
}
return isValid;
}
/*Validation start*/
/*check names, email, password confirmation*/
function validatePassword(pw, options) {
// default options (allows any password)
var o = {
lower: 2,
upper: 0,
alpha: 0,
/* lower + upper */
numeric: 1,
special: 0,
length: [0, Infinity],
custom: [ /* regexes and/or functions */ ],
badWords: [],
badSequenceLength: 0,
noQwertySequences: false,
noSequential: false
};
for (var property in options)
o[property] = options[property];
var re = {
lower: /[a-z]/g,
upper: /[A-Z]/g,
alpha: /[A-Z]/gi,
numeric: /[0-9]/g,
special: /[\W_]/g
},
rule, i;
// enforce min/max length
if (pw.length < o.length[0] || pw.length > o.length[1]) return false;
// enforce lower/upper/alpha/numeric/special rules
for (rule in re) {
if ((pw.match(re[rule]) || []).length < o[rule]) return false;
}
// enforce word ban (case insensitive)
for (i = 0; i < o.badWords.length; i++) {
if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1) return false;
}
// enforce the no sequential, identical characters rule
if (o.noSequential && /([\S\s])\1/.test(pw)) return false;
// enforce alphanumeric/qwerty sequence ban rules
if (o.badSequenceLength) {
var lower = "abcdefghijklmnopqrstuvwxyz",
upper = lower.toUpperCase(),
numbers = "0123456789",
qwerty = "qwertyuiopasdfghjklzxcvbnm",
start = o.badSequenceLength - 1,
seq = "_" + pw.slice(0, start);
for (i = start; i < pw.length; i++) {
seq = seq.slice(1) + pw.charAt(i);
if (
lower.indexOf(seq) > -1 || upper.indexOf(seq) > -1 || numbers.indexOf(seq) > -1 || (o.noQwertySequences && qwerty.indexOf(seq) > -1)) {
return false;
}
}
}
// enforce custom regex/function rules
for (i = 0; i < o.custom.length; i++) {
rule = o.custom[i];
if (rule instanceof RegExp) {
if (!rule.test(pw)) return false;
} else if (rule instanceof Function) {
if (!rule(pw)) return false;
}
}
// great success!
return true;
}
function vPass2() {
if ($.isNumeric(fname)) {
$("#fname").attr('class', 'invalid');
$.notifyBar({
cls: "error",
html: "Ad ancaq hərflərdən ibarət olmalıdır"
});
return false;
}
if ($.isNumeric(lname)) {
$("#lname").attr('class', 'invalid');
$.notifyBar({
cls: "error",
html: "Familiya ancaq hərflərdən ibarət olmalıdır"
});
return false;
}
if ($.isNumeric(mname)) {
$("#mname").attr('class', 'invalid');
$.notifyBar({
cls: "error",
html: "Atanızın adı ancaq hərflərdən ibarət olmalıdır"
});
return false;
}
if (!emailReg.test(email)) {
$.notifyBar({
cls: "error",
html: "Email ünvanınızı düzgün daxil edin"
});
$("#email").attr('class', 'invalid');
return false;
}
if (pass != confirm_pass) {
$.notifyBar({
cls: "error",
html: "Şifrə ilə təkrar şifrə üst-üstə düşmür"
});
$("#pass").attr('class', 'invalid');
$("#confirm_pass").attr('class', 'invalid');
return false;
}
if (!validatePassword(pass)) {
$.notifyBar({
cls: "error",
html: "Şifrə minimum 2 hərif və 1 rəqəmdən ibarət olmalıdır."
});
$("#pass").attr('class', 'invalid');
$("#confirm_pass").attr('class', 'invalid');
return false;
}
return true;
}
function validate() {
if (vPass1()) {
if (vPass2()) {
return true;
}
} else {
$.notifyBar({
cls: "error",
html: "Qırmızı ilə qeyd olunan xanalara tələb olunan məlumatları daxil edin"
});
return false;
}
} /*Validation End*/
$(document).ready(function () {
$('#signup_form').get(0).reset()
$("#signup_form").submit(function (e) {
fname = $("#fname").val();
mname = $("#mname").val();
lname = $("#lname").val();
email = $("#email").val();
pass = $("#pass").val();
confirm_pass = $("#confirm_pass").val();
//check the form is not currently submitting
if ($(this).data('formstatus') !== 'submitting') {
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
//add status data to form
form.data('formstatus', 'submitting');
if (validate()) {
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success: function (data) {
//setup variables
var responseData = jQuery.parseJSON(data),
cl, text;
//response conditional
switch (responseData.status) {
case 'error':
cl = 'error';
text = 'Qeydiyyat zamanı problem yarandı';
break;
case 'success':
cl = 'success';
text = 'Qeydiyyat uğurla başa çatdı';
break;
}
$.notifyBar({
cls: cl,
html: text
});
}
});
//prevent form from submitting
e.preventDefault();
} else {
return false
}
}
});
});
These two plugins may greatly simplify this for you:
jQuery Form Plugin
jQuery Form Validation
If you are using ajax to submit a form, I highly recommend the first one. It will save you a lot of code and frustration.

Categories