473,405 Members | 2,176 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

regEx in Javascript

Hi,

I'm new to javascript and regEx and trying to solve the following
problem.

I have a function which validates the password if there is a number:
-------------------------------------------------
function findNumeric(str_obj){
regEx = /\d/;
if (str_obj.match(regEx))
return true;
else
return false;
}
--------------------------------------------------
The problem arises when I put a password with a space in between e.g:
'test test1'. The fucntion returns false. I've tried '\s' in the
regEx but the user can put the space anywhere..

Any idea how to solve this problem as I should be able to put any
alplanumeric value into the password, including space.

Thanks a lot.

Vish
Jul 23 '05 #1
6 1925
Any idea how to solve this problem as I should be able to put any
alplanumeric value into the password, including space.

Thanks a lot.

Vish


Maybe you should define it global:

/\d/g
Jul 23 '05 #2
In a land long ago, in a time far away
vi******@hotmail.com (Vishant) wrote:
Hi,

I'm new to javascript and regEx and trying to solve the following
problem.

I have a function which validates the password if there is a number:
-------------------------------------------------
function findNumeric(str_obj){
regEx = /\d/;
if (str_obj.match(regEx))
return true;
else
return false;
}
--------------------------------------------------
The problem arises when I put a password with a space in between e.g:
'test test1'. The fucntion returns false. I've tried '\s' in the
regEx but the user can put the space anywhere..


Others here might correct me, but I'm pretty sure that:
function findNumeric(str_obj)
{
return str_obj.match(/\d/);
}
does exactly what you want, even with strange inputs like "test test1".

You're sure the problem comes from the "space or no space"?
--
Yours
P
Jul 23 '05 #3
Vishant wrote on 07 jun 2004 in comp.lang.javascript:
function findNumeric(str_obj){
regEx = /\d/;
if (str_obj.match(regEx))
return true;
else
return false;


Use test()

=======
This returns true if at least 1 char is a number:

function findNumeric(str_obj){
return /\d/.test(str_obj)
}

=======
This returns true if all chars are numbers,
and the string is not empty:

function findNumeric(str_obj){
return /^\d+$/.test(str_obj)
}

=======
This returns true if all chars are numbers or whitespace,
and the string is not empty:

function findNumeric(str_obj){
return /^[\d\s]+$/.test(str_obj)
}

=======
This returns true if all chars are numbers,
starting and ending white space allowed,
and the string is not empty:

function findNumeric(str_obj){
return /^\s*\d+\s*$/.test(str_obj)
}

not tested!

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 23 '05 #4
Here is a function I wrote to validate passwords in Javascript.

Rules:
1. capital and lower-case letters
2. at least one digit
3. not the same as their user name
4. not the same as the old password
5. not blank
6. minimum length
7. at least one letter
8. no white-space
9. does not contain certain names
There are a couple of things here that aren't best-practice,
but I was required to tack this on to an existing
web application, without the freedom to do much to
the original form. I hope you find some of this
to be helpful.
To answer your original question, here is a quickie
that may be helpful.

function checkForDigit(strTest){

if (strTest.match(/\d/)){
alert('\'' + strTest + '\' contains a digit');

if (strTest.match(/^\d+$/)){
alert('\'' + strTest + '\' is completely numeric.');
}

}else{
alert('\'' + strTest + '\' does not contain a digit');
}

}

checkForDigit('nstaoheu');
checkForDigit('nst4oheu');
checkForDigit('a');
checkForDigit('4');


Shawn

//password validation.js
function validatePass(formName, oldPass, newPass1, newPass2){
//function written on September 18th, 2003
//by Shawn Milochik (Milo LinuxMail Org)
//
//Revisions: none
//

//declare variables we will use
var returnValue = true; //will decide whether or not to submit the
form

var strOldPass = eval('document.' + formName + '.' + oldPass +
'.value');
var strNewPass1 = eval('document.' + formName + '.' + newPass1 +
'.value');
var strNewPass2 = eval('document.' + formName + '.' + newPass2 +
'.value');
var errMessage = '';
//For testing, to show what was entered for the old
//and new passwords
//alert(strNewPass1 + ', ' + strNewPass2);

var minLength = 7; // change this to change the minimum password
length
var strUID = document.location + ''; //get the querystring from the
browser so we can get the Uid

//Time-limited test stuff
//replace the actual querystring with the sample
//pulled from the real page
if (new Date('9/26/2003 15:00:00') > new Date()){
alert('testing mode, using fake querystring');
strUID = 'http://gebis/mstr7/ChangePassword.asp?Server=GDRDWEB01&Project=GEBIS+ %28Production%29&ProjectId=7FFAF9AC11D4F6015000839 03038D204&Port=0&Uid=dwuser&UMode=1';
}


//get the Uid from the querystring, and put it in strUID
//of the Uid in the querystring.
strUID = strUID.replace(/^.*\&Uid=(\w+)\&.*$/, "$1");

// Regular Expression translation for above:
// ^ = beginning of the line
// . = any character
// * = any number of the preceeding value, including zero
// \& = & (& is a special character, and needs to be
escaped)
// Uid = find the string "Uid"
// \w = a word character (a-z, A-Z, 0-9, _)
// + = one or more consecutive positions
// \& = & (& is a special character, and needs to be
escaped)
// . = any character
// * = any number of the preceeding value, including zero
// $ = the end of the line
//
// Using parenthesis around part of the expression allows us
to use
// the matching text in the replace function. In this case,
(\w+)
// allowed us to return whatever \w+ matched as $1. If we
had used
// another set of parenthesis, we could refer to the second
one as
// $2, and so on.
//
//See "Mastering Regular Expressions" by Jeffrey Friedl for all
this and more.
//

//************************************************** ********
// Rule: Must contain both upper and lower case
//************************************************** ********
//Check for all lower-case
if (strNewPass1.toLowerCase() == strNewPass1){
//alert('New password must contain at least one upper-case
character.');
errMessage = errMessage + '\n' + 'New password must contain at
least one upper-case character.';
returnValue = false;
}

//Check for all upper-case
if (strNewPass1.toUpperCase() == strNewPass1){
//alert('New password must contain at least one lower-case
character.');
errMessage = errMessage + '\n' + 'New password must contain at
least one lower-case character.';
returnValue = false;
}
//************************************************** ********
// Rule: password does not match the user name
//************************************************** ********
if (strNewPass1 == strUID){
alert('New password may not be the same as your user ID.');
returnValue = false;
}
//************************************************** ********
// Rule: new password is the same in both password boxes
//************************************************** ********
if (strNewPass1 != strNewPass2){
alert('New passwords do not match.');
returnValue = false;
}

//************************************************** ********
// Rule: password is not the same as the old
//************************************************** ********
if (strNewPass1 == strOldPass){
alert('New passwords may not be the same as the old one.');
returnValue = false;
}
//************************************************** ********
// Rule: password is not blank
//************************************************** ********
if (strNewPass1 == ''){
alert('New password may not be left blank.');
returnValue = false;
}
//************************************************** ********
// Rule: password meets minimum length requirements
//************************************************** ********
if (strNewPass1.length < minLength){
alert('New password may not less than ' + minLength + '
characters long.');
returnValue = false;
}

//************************************************** ********
// Rule: password does not contain the name of a Campbell brand
//************************************************** ********
if (strNewPass1.match(/((arnotts|campbell|franco|godiva|homepride|pace|pr ego|stockpot|swanson|v-?8|pepperidge|goldfish))/)){
alert('New password may not contain the name of a Campbell
brand.');
returnValue = false;
}
//************************************************** ********
// Rule: password contains at least one letter
//************************************************** ********
if (strNewPass1.match(/^[0-9]+$/)){
alert('New password must contain both letters and numbers.');
returnValue = false;
}

//************************************************** ********
// Rule: password contains at least one digit
//************************************************** ********
if (strNewPass1.match(/^[a-zA-Z]+$/)){
//alert('New password must contain both letters and numbers.');
errMessage = errMessage + '\n' + 'New password must contain both
letters and numbers.';
returnValue = false;
}

//************************************************** ********
// Rule: password contains no spaces, tabs, etc
//************************************************** ********
if (strNewPass1.match(/\s/)){
//alert('New password may not contain spaces.');
errMessage = errMessage + '\n' + 'New password may not contain
spaces.';
returnValue = false;
}
if (returnValue == false){ alert(errMessage); }

//if this returns false to the onSubmit() function within
//the <form> tag, then the form submission will be cancelled
return returnValue;

}
Jul 23 '05 #5
vi******@hotmail.com (Vishant) wrote in message news:<24**************************@posting.google. com>...
Hi,

I'm new to javascript and regEx and trying to solve the following
problem.

I have a function which validates the password if there is a number:
-------------------------------------------------
function findNumeric(str_obj){
regEx = /\d/;
if (str_obj.match(regEx))
return true;
else
return false;
}
--------------------------------------------------
The problem arises when I put a password with a space in between e.g:
'test test1'. The fucntion returns false. I've tried '\s' in the
regEx but the user can put the space anywhere..

Any idea how to solve this problem as I should be able to put any
alplanumeric value into the password, including space.

Thanks a lot.

Vish

rather, use:
bool=regex.test(str_obj)

The match method returns an array of matches, so it is unclear as to
how it responds to a true/false test (at least unclear to me!). The
"test" method is straightforward true/false here.
Jul 23 '05 #6
JRS: In article <c2**************************@posting.google.com >, seen
in news:comp.lang.javascript, Shawn Milo <ne********@linurati.net>
posted at Mon, 7 Jun 2004 09:46:39 :
Here is a function I wrote to validate passwords in Javascript.

Rules:
1. capital and lower-case letters
2. at least one digit
3. not the same as their user name
4. not the same as the old password
5. not blank
6. minimum length
7. at least one letter
8. no white-space
9. does not contain certain names
Test 5 is superfluous, if any of 1, 2, 7 is passed.
Test 7 is superfluous, if 1 is passed.

var strOldPass = eval('document.' + formName + '.' + oldPass +
'.value');
One who uses eval for that task has evidently not read the FAQ, and has
but a poor understanding of the language. The rest of the code is not
necessarily faulty.

if (new Date('9/26/2003 15:00:00') > new Date()){
The default assumption in this newsgroup is that code is for the World-
Wide Web, and may be executed by any approximately-current browser.
That date form is used, in ordinary life, only by Americans and a few
wannabes; indeed, it conflicts with a FIPS as well as with ISO. Can one
be sure, therefore, that it will always be interpreted as the 26th day
of the 9th month of 2003, and not as 2005 Feb 9th - and, if so, on what
basis?

The form new Date('2003/09/26 15:00:00') is safer, is more nearly
compliant with ISO & FIPS, and is most unlikely to be interpreted as
2005 Feb 9th. // 2003-09-26 fails, at least in MSIE4.

if (returnValue == false){ alert(errMessage); }


Better as if (!returnValue) ...

Vishant : <URL:http://www.merlyn.demon.co.uk/js-valid.htm> may help you.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Lord Khaos | last post by:
If I am trying to find an expression, foo, I can do something like this: rExp = /foo/gi; if(results.search(rExp) > -1){ and all work fine. however, if I want my search term to be a...
3
by: Jon Maz | last post by:
Hi All, Am getting frustrated trying to port the following (pretty simple) function to CSharp. The problem is that I'm lousy at Regular Expressions.... //from...
3
by: Chris | last post by:
I need to write a function that will remove a specified parameter from a URL. For example: removeParam("param1", "http://mysite.com/mypage.htm?param1=1&param2=2"); would return: ...
2
by: Mr.Clean | last post by:
I am working on modifying a syntax highlighter written in javascript and it uses several regexes. I need to add a language to the avail highlighters and need the following regexes modified to...
0
by: Chris McKenzie | last post by:
Hi, I'm using IE 6, and I'm doing some RegEx replacement on the client. Here's my code: regExStr = "\\d{2}:\\d{2}"; // where pattern matches ##:## regExStr += "(?=\\s)"; // and the next...
13
by: The Cleaning Wonder Boy | last post by:
Could someone please explain to me what the (?<Key> and (?<Value> are in the following Regex expression? This gets relative links in an HTML string (file). ...
3
by: jab3 | last post by:
Hello. I"m new to this group, and to JavaScript in general, so please forgive me if I breach local etiquette. I'm trying to implement some client-side 'dynamic' validation on a form. I'm having...
2
by: shapper | last post by:
Hello, I am trying to validate a value using Regex. How can I do this with Javascript? Thanks, Miguel
9
by: kummu4help | last post by:
can anyone give me a regex to validate the password with following conditions hope i am clear. i tried with ctype_alnum() function in php but it is accepting if all characters or either...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.