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
Related
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 ()
I am trying to validate textarea onkeyup (in real time). The goal is to allow only words starting with this character: "ch or Ch". I put together some code, but it does not work and I dont know what is wrong...
<form method="post">
<textarea name="test" pattern="ch+" id="test" onkeyup="validateTextarea"></textarea>
</form>
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
Here is the fiddle: https://jsfiddle.net/jbtRU/93/
The thing I want to do, is to disable all words in the textarea and allow only words starting with "Ch" or "ch"...
you need to bind the keyup event as below
see working fiddle https://jsfiddle.net/jbtRU/106/
$(function() {
$('#test').on('keyup', function(e) {
e.preventDefault();
var errorMsg = "Please match the format requested.";
var textarea = $(this);
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
$.each(textarea.val().split("\n"), function (key, value) {
// check if the line matches the pattern
var hasError = !value.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
});
});
It's simple validation module. Now, i can't understand why my functions (validateEmail) can't call successful. I have no js errors, but browser do postback with my form thorought validation code
<script type="text/javascript">
var Validation;
(function (Validation) {
var FormValidator = (function () {
function FormValidator(formid) {
this.emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
this.formID = formid;
}
FormValidator.prototype.Validate = function () {
var errorsSum;
$('#' + this.formID).find('input[type="text"][validate], textarea[validate]').each(function (index, item) {
var validateType = $(item).attr('validate');
switch(validateType) {
case 'text':
case 'password': {
errorsSum += FormValidator.prototype.validateText(item);
break;
}
case 'email': {
errorsSum += FormValidator.prototype.validateEmail(item);
break;
}
}
});
return errorsSum == 0;
};
FormValidator.prototype.validateGeneric = function (element, validationFunc) {
var jqElement = $(element);
alert('tested element = ' + jqElement);
if(validationFunc(jqElement.val())) {
alert('tested element error = ' + jqElement.val());
element.removeClass('error');
return 0;
} else {
element.addClass('error');
}
alert('tested element success = ' + jqElement.val());
return 1;
};
FormValidator.prototype.validateEmail = function (element) {
return FormValidator.prototype.validateGeneric(element, function (elementValue) {
return FormValidator.prototype.emailPattern.test(elementValue);
});
};
FormValidator.prototype.validateText = function (element) {
return FormValidator.prototype.validateGeneric(element, function (elementValue) {
return elementValue != '';
});
};
return FormValidator;
})();
Validation.FormValidator = FormValidator;
})(Validation || (Validation = {}));
</script>
This is my form
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #id = "register-form", #class = "form-horizontal"}))
{
...
#Html.TextBoxFor(m => m.Email, new { #placeholder = #L("Email"), #name = "email", #validate = "email" })
...
}
This is validation code
<script type="text/javascript">
$(function () {
$('#register-form').submit(function() {
return (new Validation.FormValidator('register-form').Validate());
});
});
</script>
I don't understand js so deep
You need to catch the submit event and prevent it from firing, validate the form, then submit if it was valid. Right now you are running the javascript as soon as it's submitted, but it just keeps submitting anyway since you don't stop the http request from being made.
On a related note, this is a huge mess. You don't need anything close to that much code just to validate emails and text presence on your form. This is all you need:
var validate = function(form){
var form_valid = true;
form.find('input[validate], textarea').each(function(index, el){
var type = el.attr('validate');
if (type == 'email') {
if (!el.match(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) { form_valid = false; el.addClass('error'); }
}
if (type == 'text') {
if (!el.val() == '') { form_valid = false; el.addClass('error'); }
}
});
return form_valid
}
$('#register-form').on('submit', function(){
validate($(this)) && $(this).submit()
});
Hope this helps...
Edit: made the example a bit more modular
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
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.