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;
});
});
});
Related
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();
}
}
});
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 ()
Have Text Area were we enter semicolon separated values, able to process for the keyboard events and validating successfully.How to validate the same on copy paste.
$(function () {
var kpi = document.getElementById('<%=this.d.ClientID%>').value;
var tb = $('#<%= TextBox.ClientID %>');
$(tb).keypress(function (e) {
var regex = new RegExp("[0-9;]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str) && !($(this).val().match(/;{2,}/))) {
var as = $(this).val().match(/;/ig) || [];
var len = as.length;
if (len < kpi) {
return true;
}
}
e.preventDefault();
return false;
});
$(tb).keyup(function (e) {
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (($(this).val().match(/[;]{2,}/g))) {
var shortenedString = $(this).val().substr(0, ($(this).val().length - 1));
$(this).val(shortenedString);
return true;
}
e.preventDefault();
return false;
});
$(tb).on('paste input propertychange', function (e) {
//Validate interger with ; on paste and rest not allowed
})
});
You could try using the keyup event to post-validate the input. The pasted value in the textarea is not available before this, such as at keypress. You can determine if it's a paste by checking, for example:
event.ctrlKey
You can use the keyup event, the alternative try to your implementation can be something like this:
$(tb).live('keyup', function (e) {
this.value = this.value.replace(/[;]{2,}/g, "");
}
});
This will replace semicolon from the entered value on doing paste to the textarea.
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
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