I am trying to validate zip codes using an if function with a regex. Can this be done? I currently just have the if function making sure the zip code is 5 numbers.
below is the regex i want to use
(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)
Can someone show me where and how i would add this to the if function below?
var value = $(this).val();
if( value.length<5 || value==$(this).attr('id') ) {
$(this).addClass('error');
error++;
} else {
$(this).addClass('valid');
}
var ZipCode = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (ZipCode.test(98800)) {
// true
} else {
// false
}
Try this
Try this
var filter = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (!filter.test($(this).attr('id').value)) {
$(this).addClass('error');
error++;
}
else
{
$(this).addClass('valid');
}
Related
I am getting values from a model, but while checking the values it always goes in to the else part of the conditions. I am alerting the values I am getting and they are correct, but in the if condition it doesn't get satisfied. I even tried with ===.
$(document).ready(function() {
var mark = new Boolean(#Model.isMarketing);
var revenue = new Boolean(#Model.isRevenue);
var staff = new Boolean(#Model.isStaff);
if (revenue == true) {
$("input[name=isRevenue][value='isRevenue']").prop("checked", true);
} else if (staff == true) {
$("input[name=isRevenue][value='isStaff']").prop("checked", true);
} else if (mark === true) {
$("input[name=isRevenue][value='isMarketing']").prop("checked", true);
} else {
$("input[name=isRevenue][value='None']").prop("checked", true);
}
});
I assume that you're getting not true or "true" from #Model.isMarketing, #Model.isRevenue etc.
And never use the === in condition when you using new Boolean(true) it won't equal true with using ===.
I wanna suggest you several approaches:
1. Use !! instead of new Boolean(#Model.isMarketing);
e.g.
var mark = !!#Model.isMarketing;
2. Just remove new Boolean() and use if like:
var mark = #Model.isMarketing;
if(mark) {
//do smth.
}
else {
//do smth else
};
Also I wanna suggest how to improve your code.
$(document).ready(function () {
var trueMark = 'True';
var mark = trueMark === #Model.isMarketing;
var revenue = trueMark === #Model.isRevenue;
var staff = trueMark === #Model.isStaff;
var value = 'None';
if (revenue) {
value = 'isRevenue';
}
else if (staff) {
value = 'isStaff';
}
else if (mark) {
value = 'isMarketing';
}
$("input[name=isRevenue][value="+ value + "]").prop("checked", true);
});
Please, make sure that you're getting right values from #Model
I'm getting an array of Strings, and if the array has items I want to do one thing and if not I want to do the other. I'm not sure how to check if the array is empty of not. Also when stepping through my code in chrome debugger even if the array has items in it the length is still 0 so I can't use formErrors.length > 0.
Here's my code for getting the errors. This works fine and returns an array of error strings or an empty array:
var formErrors = validateFormData(formData);
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
Then I want to do one thing if there's no errors and another if there is. But this is the bit that won't work for me.
if (formErrors !== {}) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
}
I've tried multiple ways and nothing has worked so far. Any help is appreciated, thank you!
EDIT
I can't use the .length on the array cause the length is 0 even when it has data.
Screenshot of chrome debugger
I'm slightly confused about what people are asking sorry, i'm not an expert here is my full code to get a better understanding of what i'm trying to do.
$(document).ready(function () {
$('#submit').on("click", onSubmitForm);
function onSubmitForm(event) {
clearErrorMessages();
var formData = getFormData();
var formErrors = validateFormData(formData);
if (formErrors) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
// Do other stuff
}
}
function clearForm() {
$('#title').val("");
$('#client').val("");
$('#date').val("");
$('#status').val("planning");
$('#description').val("");
$('.type').prop('checked', false);
$('.extra').prop('checked', false);
$('#title').focus();
}
function clearErrorMessages() {
$(".uk-text-danger").html("");
}
function getFormData () {
var data = [];
data["title"] = $('#title').val();
data["client"] = $('#client').val();
data["date"] = $('#date').val();
data["status"] = $('select#status option:selected').val();
data["description"] = $('#description').val();
if ($("input[name='type']:checked").length > 0) {
data["type"] = $("input[name='type']:checked").val();
}
else {
data["type"] = "";
}
data["extras"] = [];
$.each($("input[name='extras[]']:checked"), function(index, radio) {
data["extras"].push(radio.value);
});
return data;
}
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
function displayFormErrors(errors) {
for (var field in errors) {
var errorElementId = field + "Error";
$('#' + errorElementId).html(errors[field]);
}
} });
Sorry if this is too much i'm not sure what else to do.
An empty array, string or object is "falsy" in JavaScript.
That is, you can pass the array, string or object directly into the if conditional and it will run depending on if something is in there or not.
if ([]) {
// this will never run
}
if ('') {
// this won't run either
}
if ({}) {
// nor will this
}
var errors = {}; inside the validateFormData function.
And then compare the the object like this.
if (JSON.stringify( formErrors ) !== '{}') { //do something}else { //do something}
Where are you verifying if the formErrors is empty? This verification (the if-else) should be inside the function which submits the form.
Also try using:
if (formErrors.length > 0)
instead of:
if (formErrors !== {})
I need to validate the extension of an uploading file in js.I have successfully created a fuction like as follows.
function FileExtension_Validate(txt)
{
if( !txt.match(/\.(pdf)|(doc)|(PDF)|(DOC)|(docx)|(DOCX)$/)) { return false; } else {return true; }
}
But now my situation is, i have a database field which have data as follows
pdf,doc,PDF,DOC,docx,DOCX
Now i need to create a function based on the data from database.Is there any possible solution.Please help me..?
I solved it as follows..
function FileExtension_Validate(txt)
{
//alert(txt);
var extension=document.getElementById('extension').value;
var piece = extension.split(',');
var split=extension.split(',').length
var flag=0;
//alert(piece[0]);
for (var i = 0; i <split; i++)
{
var test=piece[i];
//alert(test);
if( txt!=test) { flag++;}
//else {return true; }
}
// alert(flag);
if(flag==split)
{
return false;
}
else{
return true;
}
in extension i have passed the extension of the uploade file
I am using jQuery Steps plugin (LINK HERE). Problem is in one IF statements that returns wizzard to first step (not on step that is currently indexed). All IF statements are working correctly expect this one. That if statemnt is checking if phone number is in correct format:
Here is code:
onFinishing: function (event, currentIndex) {
var filter = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!filter.test($("#email").val())) {
$("#emailError").text("e-mail is wrong");
return false;
}
if (!filter.test($("#email2").val())) {
$("#email2Error").text("e-mail is wrong");
return false;
}
var newnum = parseInt($("#numppl").val());
if(Math.floor(newnum) != newnum && !$.isNumeric(newnum)){
$("#numpplError").text("Number error");
return false;
}
if (!($("#numppl").val() >= 1 && $("#numppl").val()<=10)){
$("#numpplError").text("Number error");
return false;
}
if ($("#email").val()!=($("#email2").val())){
$("#email2Error").text("address don't match");
return false;
}
/*IF Statment bellow is bugged */
if ($("#phone").length) {
if(!$("#phone").match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)){
$("#phoneError").text("Wrong format");
return false;
}
}
return true;
},
Make correction in IF Statement in which you commented as bug :
pval = $("#phone").val(); //Store the value of "Phone"
if (pval.length) { //Check for non empty
if(!pval.match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)) { // Check format.
$("#phoneError").text("Wrong format");
return false;
}
}
$("#phone").length isn't same as the length of phone number
inspite of $("#phone").length use ($("#phone").val()).length
similarly inspite of $("#phone").match(regular Expression) use
($("#phone").val()).match(regular Expression)
I have a simple form which users can enter a "tweet". I ahve some javascript behind the scenes to control what happens when a url is entered.
If a url is entered such as test.com then a new input field will appear.
If a url that is stored in an array is entered, it will and the new input field along with a select option.
here is my javascript:
var test = ["test1.com", "test2.com", "test3.com"];
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keydown(function () {
var val = this.value;
if (/\.[a-zA-Z]{2,3}/ig.test(val)) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
if ($.inArray(val, test) !== -1) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
});
It works fine if just a url is entered. But as soon as you add more text, it disregards if the url is in the array, and removes the select option. I'm not quite sure on how to explain this any better, so i have setup a fiddle to show what i mean.
I hope someone understands and can point me in the right direction
Fiddle
That's because you are checking if a whole input is in the array: if ($.inArray(val, test) !== -1). You need to retrieve URL from the input using a regex and check that.
Write a regex that retrieves any URL, get that URL and check if it's one of your lucky ones:
var urlsInInput = /[a-z0-9]+\.[a-zA-Z]{2,3}/ig.exec(val);
if (urlsInInput.length == 1 && $.inArray(urlsInInput[0], test) !== -1) {
instead of
if ($.inArray(val, test) !== -1) {
Fiddle
Here is my version handling the first url
Live Demo
$('#tweet_text').keydown(function () {
var val = this.value;
var urls = val.match(/[a-z0-9]+\.[a-zA-Z]{2,}/ig);
var alias = (urls && urls.length>0)
$('#custom_alias').toggle(alias);
var tweet = urls && urls.length>0 && $.inArray(urls[0], test) !== -1;
$('#tweet_campaign').toggle(tweet);
});
What #siledh said. Here is how you could use your current test array
var reg = new RexExp(test.join('|').replace(/\./ig, "\\."), 'ig')
if( reg.test(val) ) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
The reason the campaign field begins to disappear again is that you compare the whole value of the input with the array. If you just find all domain matches and then compare them to your array it should work.
Like so:
var test = ["test1.com", "test2.com", "test3.com"];
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keyup(function () {
var alias = false;
var campaign = false;
var domain = /([a-z0-9]+(:?[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})/ig;
var val = this.value;
var match = val.match(domain);
if (match) {
alias = true;
match.forEach(function(e) {
campaign = campaign || ($.inArray(e, test) !== -1);
});
}
if (alias === true) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
if (campaign === true) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
});
Something wrong with your $.isArray(val, test), the value you use is the whole value.
And not sure your purpose, so write a code like this. hope it would help.
http://jsfiddle.net/sheldon_w/KLuK8/
var test = ["test1.com", "test2.com", "test3.com"];
var urlReg = /[^\s]+\.[a-zA-Z]{2,3}/ig;
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keydown(function () {
var val = this.value;
var matchedUrls = [];
val.replace(urlReg, function (matched) {
matchedUrls.push(matched);
});
if (matchedUrls.length > 0) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
$(matchedUrls).each(function (idx, url) {
if ($.inArray(url, test) !== -1) {
$('#tweet_campaign').show();
return false;
} else {
$('#tweet_campaign').hide();
}
});
});