Javascript regex function wont initiate - javascript

I need to perform some validation using regular expressions in Javascript.
8 out of 10 of my regex validations work like a charm except this one, I have tried many changes in my regex and code, ran in firebug, dreamweaver, multiple browsers, the code will not alert, the problem lies in the function and i cannot point my finer on it.
here is a testing version of my code:
function validate_DOB()
{
var regexDOB = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)([0-9]){4}$/i;
var checkDOB = "jan1888";//document.form.DateofBirth.value;
if (regexDOB.test(checkDOB) == false)
{
alert("Date of birth must be in the following format: jan1990(example)");
//document.form.DateofBirth.focus();
return false;
}
else if (2014 - eval(checkDOB.substr(3,4)) < 19)
{
alert("You must be at least 19 years of age");
//document.form.DateofBirth.focus();
return false;
}
else
{
alert("true");
return true;
}}// validate DOB
validate_DOB();
Any help is greatly appreciated, thank you.

Related

/ operator (or some other part of the code) doesn't seem to work

I wrote a simple code in javascript that was supposed to validate the length of a phone number inputed in an html form (check if it consists of 10 digits- as it is in my country).
So here's the function:
function check_tel(){
var tel=document.LpData.phone.value;
var i=0;
for(;i<10;i++){
tel/=10;
if(tel==0){
alert("unvaild phone number- too short");
return false;
}
}
if(tel>0){
alert("unvaild phone number- too long");
return false;
}
return true;
}
But it always outputs that the number is too long (i>10).
I already checked the value of "tel" variable before it enters the loop and everything is right.
I also tried it with a "while" instead of "for" loop.
So I concluded it's because of the "/" operator which doesn't work (although I still don't understand how it's possible) or it has something to do with the type of tel...
So what is the problem and how to fix it?
Thanks in advance!
Every input value is always a string. Using the divide operator on a string is not what you wanted. So you may convert the phonenumber to an int:
function check_tel(){
var tel=parseInt(document.LpData.phone.value,10)||0;
for(var i=0;i<10;i++){
tel/=10;
if(tel<1){
alert("unvaild phone number- too short");
return false;
}
}
tel/=10;
if(tel>1){
alert("unvaild phone number- too long");
return false;
}
return true;
}
also note that 123456789/10000000 is not 0...
and by the way, it is much easier to simply check for tel.length...
The best practice to do these things is to use a Regular Expression(Regex).
/^\d{10}$/ is a JS regex to check if the number is a 10 digit number.
function check_tel()
{
var tel = document.LpData.phone.value;
var teleRegex =/^\d{10}$/;
if(!teleRegex.test(tel)){
alert("invalid phone number")
}
else{
//do your thing
}
}
Possible work-around is
function check_tel()
{
var tel=document.LpData.phone.value;
if(tell.length == 0 || tell.length > 10){
alert("invalid phone number");
return false;
}
return true;
}
Try var tel = parseInt(document.LpData.phone.value); instead of var tel = document.LpData.phone.value;

Working With ifNan Function

I'm having trouble getting the Codecademy section of ifNan done. How do I make it so the ifNan function checks the number I manually input at the end when I run the function. For example:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (isNan(number)) {
return "Your input is not a number!";
} else {
return false;
}
};
isEven(2);
What would I put in the isNan function so that when I input the number at the bottom it also checks if it is actually a number?
you could condense that down to:
function isEven(number)
{
if(!isNaN(number) || number % 2 === 0)
{
return true;
}
return false;
}
See elclanrs comment. isNan is not a function isNaN is. caps matter there.
So...update to this long-standing issue:
I went back to codecademy and restarted the lesson. After researching for about a week, and a good long breather, I came back to this frustrating issue and even then found myself writing the same exact code that I had in the beginning of this issue (because I knew it was correct).
You all made valid points.
Dennis you're absolutely right this can be condensed in a few areas but Codecademy is very rigid (which I'm liking less and less) so it would have never let me pass the dang section.
Anyways, I wanted to close this but "answer" (kind of) it first.
Thanks for all your assistance.
Try this:
var isEven = function(number) { if (number % 2 === 0) { return true; } else if(isNaN(number) === true || false){ return "your input is not a number"; } else { return false; }// Your code goes here!
}; isEven("Gbemi")

textbox must contain number or letter validation on javascript without regex

Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.

Jquery Validation with SSN Regex, Masked Input and Depends

I'm having trouble getting the Jquery Validation to work with the following rules.
I have the field masked with SSN format, the validation must not allow submission of this information without it being a complete SSN. I have a working regex function that rejects non SSNs. I need it to not allow blank submissions as well (the mask is only applied if the field is onFocus). And last but not least, the field is NOT required if another checkbox is checked (#noSSN).
I've added a JSfiddle page to help: http://jsfiddle.net/B2UpW/3/
It appears to be working a bit different on the fiddle page. Hope this helps!
Edit: I've yet to receive any responses.. curious if there is any confusion about my question? Any suggestions to help find some assistance is welcome!
$("#ssn").mask("999-99-9999");
$.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value !== param;
}, "Please choose a value!");
$("#applicantForm").validate({
rules: {
ssn: {
notEqual: "___-__-____",
required: {
depends: function(element) {
return ($("#ssn").val() == ""
|| isValidSSN($("#ssn").val())
|| $("#noSSN:unchecked"));
}
}
}
},
messages: {
ssn: 'Please enter a social security number.'
}
});
function isValidSSN(value) {
var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
if (!re.test(value)) { return false; }
var temp = value;
if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
if (temp.substring(0, 3) == "000") { return false; }
if (temp.substring(3, 5) == "00") { return false; }
if (temp.substring(5, 9) == "0000") { return false; }
return true;
}
Website owners, please stop using the piece of code from jammypeach or Stephen S. above. Some valid SSNs are rejected by their regexp.
See http://www.socialsecurity.gov/employer/randomization.html
Previously unassigned area numbers were introduced for assignment
SSNs can start with "773" and above since June 2011, before that thread was created.
Please replace ([0-6]\d{2}|7[0-6]\d|77[0-2]) with \d{3} - now I have to go to the bank in person because of you ;-)
You just needed to add a check to see if the checkbox was, er, checked.
See this updated fiddle, around line 9 (or line 2 in the code below) where you check if the SSN is valid:
$('#submitApplication').live('click', function() {
if ($('#noneSSN').is(':checked'))
{
alert("SUCCESS");
}
else
{
var isValid = $("#applicantForm").valid();
if (isValid) {
alert("SUCCESS");
}
}
return false;
});
It will now allow a submit if the box is checked, otherwise it will demand a correct SSN.
It's not very clear what is not working exactly...
I see a few things anyway:
What is notEqual? Is it a method you added ? There is an method called pattern in the additionnal methods script proposed along with the plugin.
What is the purpose of your depends ? Add a rule required to check the value is not empty and add a rule like isValidSSN: true to execute your own SSN validation.
Only use the depends (or required: function(element) { return $("#noSSN").is(":unchecked"); }) to apply the rules when the checkbox is not checked.
Hope this helps, d.

Time validation (and comparing) using Javascript / JQuery

First of all apologise for creating my third Javascript question in as many days - I'm really trying to push myself in this field on this project, and feel my skills are developing at a fairly good rate thanks to my research and your fantastic help on here, particularly redsuqare!!
I've got a table where people can enter times, and have a mask in place where it'll check that the input is in the format 99:99 - which is great, but ideally I want to limit it to be no more than 23:59!
Here's the code I have at the moment, cobbled together the best I can, but unsurprisingly doesn't work...
$.each($('#hoursavailable tr td :checkbox'), function() {
var $this = $(elem); // cache the object
var $row = $this.closest('tr'); // find the nearest table row
if($this.is(':checked')) {
// do nothing!
} else {
$row.each(':text'),function() {
var splittime = $(this).split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
}
}
});
Could also be worth noting that there are two inputs per row/tr - it'd be absolutely ideal if I could somehow compare the two, to ensure that the first one is before the second, but appreciate that could be even more beyond me than the current stuff :(
Thanks
This may be what you are looking for-
http://www.the-art-of-web.com/javascript/validate-date/
I think all you need is the following change since your doing an each around the text inputs so you need to get the value out and split that.
$row.find(':text').each(function() {
var splittime = $(this).val().split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
});
However to save yourself re-inventing the wheel why not look into the validate plugin where you can configure regex expressions to deal with data validation.
Although I do appreciate hand rolling is also a good learning curve.
You're going mad with your eaches when you really only need one
This ought to get you going with a few caveats as detailed below.
$("#hoursavailable :checked").each(function() {
var splittime = $(this).parents("tr").find(":text").val().split(":");
if (splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date');
return false;
}
});
I've assumed here that you only have one text box (hence .find(":text") on the parent. You could consider adding a class, but bear in mind that class selectors are slow.
There is no validation here, so you might want to add a little more, however the premise works.
Synthesis from different methods to check for max & format together.
var timeFieldValue = $(this).val();
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if(timeFieldValue != '' && !timeFieldValue.match(re)) {
alert("Invalid time format: " + timeFieldValue);
$(this).focus();
return false;
}
var splittime = timeFieldValue.split(":");
if(splittime[0] > 23 || splittime[1] > 59) {
alert('Please enter a valid time');
return false;
}

Categories