473,761 Members | 9,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1950
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******@hotmai l.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.javas cript:
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(s trTest){

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(fo rmName, 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(strNewPas s1 + ', ' + strNewPass2);

var minLength = 7; // change this to change the minimum password
length
var strUID = document.locati on + ''; //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=GDRD WEB01&Project=G EBIS+%28Product ion%29&ProjectI d=7FFAF9AC11D4F 601500083903038 D204&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.to LowerCase() == 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.to UpperCase() == 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.le ngth < 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.ma tch(/((arnotts|campb ell|franco|godi va|homepride|pa ce|prego|stockp ot|swanson|v-?8|pepperidge|g oldfish))/)){
alert('New password may not contain the name of a Campbell
brand.');
returnValue = false;
}
//*************** *************** *************** *************
// Rule: password contains at least one letter
//*************** *************** *************** *************
if (strNewPass1.ma tch(/^[0-9]+$/)){
alert('New password must contain both letters and numbers.');
returnValue = false;
}

//*************** *************** *************** *************
// Rule: password contains at least one digit
//*************** *************** *************** *************
if (strNewPass1.ma tch(/^[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.ma tch(/\s/)){
//alert('New password may not contain spaces.');
errMessage = errMessage + '\n' + 'New password may not contain
spaces.';
returnValue = false;
}
if (returnValue == false){ alert(errMessag e); }

//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******@hotmai l.com (Vishant) wrote in message news:<24******* *************** ****@posting.go ogle.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********@lin urati.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(errMessag e); }


Better as if (!returnValue) ...

Vishant : <URL:http://www.merlyn.demo n.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.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.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
1912
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 variable, bar: var bar= "foo";
3
2084
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 http://support.microsoft.com/default.aspx?scid=kb;EN-US;246800 function fxnParseIt() { var sInputString = 'asp and database';
3
2242
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: "http://mysite.com/mypage.htm?param2=2" I'm thinking that string.replace(/regex/, ""); would do the trick, but how
2
1875
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 parse the new language, Delphi/Pascal. Source to the highlighter is avail here: http://www.dreamprojections.com/SyntaxHighlighter/Default.aspx ********************************************** COMMENTS
0
1040
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 character is a space regExStr += "(?<=\\s\\d{2}:\\d{2})"; // and the preceding characters match " ##:##" (i.e., not ##:##:##) r = new RegExp(regExStr);
13
1574
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). "(?<Key>href=(?!#|http|ftp|mailto|javascript)(?<Value>*) )" Here is usage:
3
3986
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 a couple of problems, which I'll try to describe. But this e-mail will only reproduce one of them, in a "short" example. What I'm generally doing is having each form entry contained in a div, which as a label, an input with some event handlers,...
2
251
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
6619
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 alphabet or digit. but i want to enforce atleast one alphabet and one digit should be in password can any one give me a regex for this pls.....
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10136
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9923
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3911
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.