AJAX form submission issue - javascript

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.

Related

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 prevent two JavaScript files from executing simultaneously

I have two JavaScript files. One is running validation, and other have ajax plugin that sends form after validation.
When I attached these files in the header section, then they simultaneously run, but if I attach these two files in the body, then validation runs as it should but ajax call not working.
There is no any error on the console as well.
..
What you people suggests?
AjaxCall.js
$(document).ready(function() {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: 'quoteProcess.php', // override for form's 'action' attribute
type: 'post', // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
};
// bind 'myForm' and provide a simple callback function
$('#testform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.modal').show();
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
$('.modal').hide();
alert( '\n\nYour Quote has been Recieved ! \n' + responseText +
'\n');
window.location.replace("http://localhost/lamozine/quote.php");
}
validation.js
(function($){
var functions = {
reset: resetValidation
};
var settings;
var _reqForm;
var _indicatorTemplate = '<span class="error-indicator" role="alert" aria-live="assertive" aria-hidden="true"></span>';
var _summaryTemplate = '<div id="errorSummary" class="alert alert-danger" role="alert" aria-live="assertive" tabindex="-1"><p>{0}</p></div>';
var _validationTypes = {
required: {msg: ' is required' },
tel: {msg: ' is not a valid phone number' },
email: {msg: ' is not a valid email address' },
date: {msg: ' is not a valid date'},
number: {msg: ' is not a valid number'}
};
$.fn.attrvalidate = function() {
if (!this.is('form')) {
return this;
}
if (typeof arguments[0] === 'string') {
var property = arguments[1];
var newArgs = Array.prototype.slice.call(arguments);
newArgs.splice(0, 1);
functions[arguments[0]].apply(this, newArgs);
} else {
setupFormValidation.apply(this, arguments);
}
return this;
};
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function setupFormValidation(options){
settings = $.extend({
showFieldIndicator: true,
showErrorSummary: true,
errorSummaryMsg: 'Please fix the following issues before continuing:',
validateTel: true,
telRegex: /^\+*[\d-()]{7,20}$/,
validateEmail: true,
emailRegex: /^(\S+#\S+)*$/,
validateDate: true,
validateNumber: true
}, options);
_reqForm = this;
initialiseValidation();
$(_reqForm).bind('submit', handleSubmit);
}
function initialiseValidation(){
var _groupsInitialised = [];
$(_reqForm).find('input, select[required], textarea[required]').each(function(){
if (isRadioGroup($(this)) && $(this).is('[required]')) {
var groupName = $(this).attr('name');
if ($.inArray(groupName, _groupsInitialised) === -1) {
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
$(this).parents('fieldset').first().append($(_indicatorTemplate));
}
$(_reqForm).find('input[name="' + $(this).attr('name') + '"]').each(function(){
$(this).change(function(){
handleFieldChanged($(this));
});
});
_groupsInitialised.push(groupName);
}
} else {
if ($(this).is('[required]') ||
(settings.validateTel && $(this).is('input[type="tel"]')) ||
(settings.validateEmail && $(this).is('input[type="email"]')) ||
(settings.validateDate && $(this).is('input[type="date"]')) ||
(settings.validateNumber && $(this).is('input[type="number"]'))){
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
if (($(this).is('input[type="radio"]') || $(this).is('input[type="checkbox"]')) && $(this).next('label').length > 0) {
$(this).next('label').after($(_indicatorTemplate));
} else {
$(this).after($(_indicatorTemplate));
}
}
$(this).change(function(){
handleFieldChanged($(this));
});
}
}
});
}
function handleFieldChanged(elem){
var validationResult = validateField(elem);
if (validationResult.isValid) {
clearFieldError(elem);
} else {
var fieldMsg = getFieldMessage(elem, validationResult.type);
showFieldError(elem, fieldMsg);
}
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}
function validateField(elem){
if (!elem.is(':visible') || elem.parents('[aria-hidden="true"]').length > 0){
return { isValid: true };
}
if (elem.is('input[type="radio"]')) {
if (elem.is('[required]')){
if (isRadioGroup(elem)) {
return { isValid: ($(_reqForm).find('input[name="' + elem.attr('name') + '"]:checked').length > 0), type: _validationTypes.required };
} else {
return { isValid: elem.is(':checked'), type: _validationTypes.required };
}
} else {
return { isValid: true };
}
} else if (elem.is('input[type="checkbox"]')) {
return { isValid: (!elem.is('[required]') || elem.is(':checked')), type: _validationTypes.required };
} else {
if (elem.is('[required]') && (elem.val() === '')) {
return { isValid: false, type: _validationTypes.required };
} else if (settings.validateTel && elem.is('input[type="tel"]')) {
return { isValid: settings.telRegex.test(elem.val().replace(/ /g, '')), type: _validationTypes.tel };
} else if (settings.validateEmail && elem.is('input[type="email"]')) {
return { isValid: settings.emailRegex.test(elem.val().trim()), type: _validationTypes.email };
} else if (settings.validateDate && elem.is('input[type="date"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(Date.parse(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(Date.parse(elem.prop('max'))) && Date.parse(elem.val()) > Date.parse(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(Date.parse(elem.prop('min'))) && Date.parse(elem.val()) < Date.parse(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.date };
} else if (settings.validateNumber && elem.is('input[type="number"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(parseFloat(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(parseFloat(elem.prop('max'))) && parseFloat(elem.val()) > parseFloat(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(parseFloat(elem.prop('min'))) && parseFloat(elem.val()) < parseFloat(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.number };
} else {
return { isValid: true };
}
}
}
function setFieldName(elem){
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
return;
}
var elemName;
var forLabel = $(_reqForm).find('label[for="' + elem.attr('id') + '"]');
if (forLabel.length > 0 && $(forLabel[0]).text() !== '') {
elemName = $(forLabel[0]).text();
} else {
elemName = elem.attr('name');
}
elem.data('error-name', elemName);
}
function getFieldMessage(elem, resultType){
var elemMsg;
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
elemMsg = elem.data('error-msg');
} else {
elemMsg = elem.data('error-name') + resultType.msg;
}
return elemMsg;
}
function showFieldError(elem, fieldMsg){
if (isRadioGroup(elem)) {
elem.parents('fieldset').first().addClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
} else {
elem.addClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
}
}
function clearFieldError(elem){
if (isRadioGroup(elem)) {
elem.parents('fieldset').removeClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().attr('aria-hidden', true);
}
var firstInGroup = $(_reqForm).find('input[name="' + elem.attr('name') + '"]').first();
var summaryItem = $('#errorSummary li a[data-field="' + firstInGroup.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
} else {
elem.removeClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().attr('aria-hidden', true);
}
var summaryItem = $('#errorSummary li a[data-field="' + elem.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
}
}
function showErrorSummary(errorMsgList){
var errorSummary = $(_summaryTemplate.replace('{0}', settings.errorSummaryMsg));
var errorList = $('<ul></ul>');
for (var i=0; i < errorMsgList.length; i++) {
var errorLink = $('' + errorMsgList[i].msg + '');
errorLink.click(function(){ jumpToElem($(this).data('field')); return false; });
var errorItm = $('<li></li>');
errorItm.append(errorLink);
errorList.append(errorItm);
}
errorSummary.append(errorList).prependTo($(_reqForm));
errorSummary.focus();
}
function isRadioGroup(elem){
return (elem.is('input[type="radio"]') && typeof(elem.attr('name')) !== 'undefined' && elem.attr('name') !== '');
}
function jumpToElem(fieldId){
$(_reqForm).find('#' + fieldId).focus();
}
}(jQuery));
I am not clear with your question very well but if you want to load one script file after loading an another script file. You can simple load using $.when() and $.getScript() jquery functions like this.
$.getScript() will load javascript file asynchronously and .done() call back of $.when() method will continue after the loading script done.
This is a very simple sample.
<html>
<head>
<script src="/jquery.min.js"></script>
</head>
<body>
<script>
$.when(
$.getScript("/mypath/validation.js")
).done(function(){
$.getScript("/mypath/AjaxCall.js")
});
</script>
</body>
Hope it might help.

how can i reset #html.Listbox to empty using jquery in Asp.net MVC

#Html.ListBox("project type", new SelectList(db.tblTypes.ToList(), "ID", "Name"),
new { multiple = "multiple", id = "projectType" })
here is my ajax code where i want it to empty
$("#frm").submit(function (e) {
e.preventDefault(e);
//$('#frm').submit();
var e = document.getElementById("myselect");
var selectedIndices = [];
$(function () {
$.each($('select[multiple]'), function (sIndex, sValue) {
if (sIndex == 0) {
$.each(this.options, function (oIndex, oValue) {
if (this.selected)
selectedIndices.push(oIndex);
});
} else {
for (var i = 2; i < selectedIndices.length; i++) {
this.options[selectedIndices[i]].selected = true;
}
}
});
});
var project = {
ProjectTitle: $('#ProjectTitle').val(),
ProjectNumber: $('#ProjectNumber').val(),
Portfolio: $('#Portfolio').val(),
TotalSalesCC: $('#TotalSalesCC').val(),
grossMarginCC: $('#GrossMarginCC').val(),
projectMarginCC: $('#ProjectMarginCC').val(),
projectStatus: e.options[e.selectedIndex].value,
ImpStartDate: $('#ImpStartDate').val(),
ImpEndDate: $('#ImpEndDate').val(),
projectType: selectedIndices,
isSurvey:$('#hide').val()
};
if ($("#ProjectNumber").val() == "") {
$.growl.error({ message: 'Please fill project number.' });
return false;
}
if ($("#ProjectTitle").val() == "") {
$.growl.error({ message: 'Please fill project title.' });
return false;
}
if (selectedIndices.length == 0 || selectedIndices.length < 1) {
$.growl.error({ message: 'Please choose atleast one project type.' });
return false;
}
var s=$("#ImpStartDate").val();
var e = $("#ImpEndDate").val();
if (s == "" )
{
$.growl.error({ message: 'Please enter start date.' });
return false;
}
else if (e == "")
{
$.growl.error({ message: 'Please enter end date.' });
return false;
}
else if (s > e) {
$.growl.error({ message: 'End date should be greater than start date.' });
return false;
}
var date = new Date();
date.setDate(date.getDate()-1);
//$('#ImpStartDate').datepicker({
// startDate: date
//});
$.ajax({
type: "POST",
url: "/Projects/Create",
data: JSON.stringify(project),
contentType: "application/json; charset=utf-8",
success: function (s) {
console.log(s);
LoadProjectsGrid();
//LoadprojectsGrid();
// End For
$.growl.notice({ message: ' Your Project created successfuly' });
$("#projectType").html('');
},
failure: function (response) {
alert(response.d);
}
});
// clear list via dom
// or clear list via jquery & dom
$('#frm').find(".has-success").removeClass("has-success");
$('#frm').find(".glyphicon-ok").removeClass("glyphicon-ok");
$('.panel-collapse').collapse('hide');
$('.panel-title').attr('data-toggle', 'collapse');
document.getElementById('frm').reset();
$('#accordion .ui-accordion-content ').hide();
});
If you want to empty it on the Client side use
$("#projectType").html('');
And If you want an empty Value on the server side use
$("#projectType").val('');

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

validating This form (numbers only)?

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

Categories