Jump to content

reqular expressions problem


feck
 Share

Recommended Posts

I have a reqular expression function that i took from one of the WROX books

function regExpIs_Valid(text){	var myRegExp = /[^a-z\d ]/i;	return !(myRegExp.test(text));}

which basically checks for any character that is not alphnumeric or whitespace, although useful, I would actually like to allow 'commas, apostrophe's, colons: and full stops. Thereby allowing the user to enter these types of punctuations, as well as the already quoted regular expression check, but no other characters regardless of what they may be.Does know how to achieve this or point me in the rigtht direction

Link to comment
Share on other sites

Phew solved it.

function regExpIs_Valid(text){	var myRegExp = /[^a-z\d\.\,\'\: ]/i;	return !(myRegExp.test(text));}

Now just have to work out away that would warn me if only these punctuation marks alone were used and no alphanumeric characters.

Link to comment
Share on other sites

Now just have to work out away that would warn me if only these punctuation marks alone were used and no alphanumeric characters.
There's bound to be a cleaner solution, but this may work:
var myRegExp = /[a-z\d\.\,\'\: ]*[a-z\d]+[a-z\d\.\,\'\: ]*/i;return (myRegExp.test(text));

That'll match any string that has at least one letter or number and any number of other letters, numbers, spaces, periods, commas, single quotes, or colons.And, notice, rather than !myRegExp.test(), this uses myRegExp.test().EDIT: I would probably use [\w\s\.,':] rather than [a-z\d\.\,\'\: ] but that's just me. :)

Link to comment
Share on other sites

cheers jesh,tried your way it did'nt seem to work in my code. I'm still trying to understand yours as I'm new to expressions, but the main problem I'm having at the moment is the fact that i allow whitespace, how do i check for too much whitespace.ie; if there are more than two spaces between words.the problem is that at the moment in my validation the user can press the space bar repeatedly and this will still validate.Any suggestions?

Link to comment
Share on other sites

Hmm, I would typically accept the user input and simply replace all multiple instances of whitespace with a single whitespace character:

var reg = /\s+/g;str = str.replace(reg, " ");

And then run the validation against that new string. If you want to stick with a single regular expression, you might look into lookaheads, lookbehinds, and lookarounds. I haven't worked with these (yet) but it might do the trick. Here's a link:http://www.regular-expressions.info/lookaround.html

Link to comment
Share on other sites

thanks again jesh, I've already been looking at the lookaheads and such, but cannot seem to get them to work within my string.Also the problem with accepting the multiple whitespace is that as I stated earlier if the user tries to inject some redundant code like holding down the space bar, this will still validate whether you reduce this to one space or not.I would have to deal with this then server side which would still issue the same problem.As I'm injecting values into a database I would not want a user authorized or not to be able to insert whitespace values.The logic behind the lookarounds is facinating, but as yet i'm having trouble grasping it.So far i can check for whitespace but not how much.

Link to comment
Share on other sites

The logic behind the lookarounds is facinating, but as yet i'm having trouble grasping it.
Make that two of us!Maybe if you can provide me some examples of the data that your users will be entering, I, or someone else here, can help you come up with an expression to validate it.
Link to comment
Share on other sites

To check for something to appear more than once, doesn't a simple {#} work? Where # = the number of occurences you want to check for.\s{2} would check for 2 whitespaces i think :)
That's right. And * is "zero or more times" and + is "one or more times" and ? is "zero or once". You can also use {n,m} which is "from n to m occurances" (e.g. {2,5} is "from two to five").This site is the best I've found so far regarding regular expressions:http://www.regular-expressions.info/
Link to comment
Share on other sites

tried these different ways but still no luck:

var myRegExp = /[^a-z\d\s{2,*}\.\,\'\:]/i;var myRegExp = /[^a-z\d\s{2}\.\,\'\:]/i;var myRegExp = /[^a-z\d\s(?!\s)\.\,\'\:]/i;

Say I'm entering the names of books:The wind in the willows would be valid but the following ways would not:

The wind in the willows
The wind in the willows
or even if i was validating telephone numbers
123 456 7890
would be valid but
123 4 56 7890
would notor even just holding down the space bar
I cannot even tell you how I would like to enter invalid values, I've tried to show you what i mean twice now by reediting the post but the system strips the extra white space.So actualy this would be invalidThe "space""space""space""space""space"wind int the willowsif you get what i mean?
Link to comment
Share on other sites

For telephone numbers, it's different. You would need to match either(#)? ### ### ####or### ####So, it would be along the lines of ((\d{1}\s)?(\d{3})?\d{3}\s\d{4}Atleast, i think that's how it would be done :/By the way, i was wondering about your lines.you have \s{2,*}...would that match for only 2 spaces in the entire string, or only 2 spaces in a row...?

Link to comment
Share on other sites

What about using multiple regular expressions?

function isValid(text){	var tooManySpaces = /\s\s/;	var invalidCharacters = /[^a-z0-9\.,': ]/;	if( text.match(tooManySpaces) || text.match(invalidCharacters) )	{		return false;	}		else		{				return true;		}}

To validate a phone number, you might use something like this

function isValidPhoneNumber(text){	var phoneNumber = /([\d]{3})?\s?[\d]{3}\s?[\d]{4}/;	if( text.match(phoneNumber) )	{		return true;	}	else	{		return false;	}}

I haven't tried the expressions, so I can't guarantee that they are 100% correct but they should be close.

Link to comment
Share on other sites

Actually, use the global and multiline flags on this./regexpstuff/gim; that might solve your problem...o_O
Sorry beta dont really know what this actually meansThanks guys for trying anyway I've tried your way Jesh but it still doesnt seem to workThanks all the same
Link to comment
Share on other sites

Hmm. You might have to post your full code or at least a link to it if it is on the web. That isValid function above works for me to match "the wind in the willows" but not match "the wind in the willows" (with lots of spaces in it).

Link to comment
Share on other sites

Heres my if statement within a loop that scrolls through form values from a validation function:

if(regExpIs_Valid(elemValues[i].value) == false){ 			/*checks for values other than those			identified in the reqular expression function */			invalid_Entry += "<li>"+elemValues[i].id + " is reg invalid</li>";		}

Again heres my regular expression function

function regExpIs_Valid(text){		var myRegExp = /[^a-z\d\.\,\'\: ]/i;	return !(myRegExp.test(text));}

Link to comment
Share on other sites

So your form has various elements (one may be a book title, one may be a phone number) and you want a single validation function to validate each form field?What if, in your form, your form elements had IDs on inputs with special requirements (like phone number):

function validateForm(){var form = document.getElementById("myform");var phoneNumberReg = /([\d]{3})?\s?[\d]{3}\s?[\d]{4}/;var tooManySpacesReg = /\s\s/;var invalidCharactersReg = /[^a-z0-9\.,': ]/;var elements = form.elements;var count = elements.length;var element;// loop through all elementsfor(var i = 0; i < count; i++){	element = elements[i];	if(element.id == "phoneNumber")	{		if(phoneNumberReg.test(element.value))		{			 continue;		}		else		{			 // add your error message to invalid_Entry;		}	}	else	{		if(tooManySpacesReg.test(element.value) || invalidCharactersReg.test(element.value))		{			 // add your error message to invalid_Entry;		}		else		{			continue;		}	}}}

Link to comment
Share on other sites

Solved it too a point jesh, changed the reg exp to

var myRegExp = /([^a-z\d\.\,\'\:])+\s/i

This now correctly validates any extra whitespace than needed ie more than once: text"space""space"textThe only problem left is that for some reason the validation still occurs if there is one "space" at the start of the string even with or without any trailing text.So I can now validate for any extra whitespace but just not the first whitespace at the start of a string.

Link to comment
Share on other sites

Maybe you could perform the following steps (all client-side before the form is submitted) and it would work well 1) Do a check for length.

if(text.length == 0){	// they didn't enter anything!}

2) Replace multiple whitespace characters with a single whitespace character. This way, even if they type in a whole bunch of spaces, you can trim out those spaces and accept it as input:

text = text.replace(/\s+/g, " ");

3) Check to see if there are any invalid characters:

if( text.match(/[^a-z0-9\.,':]/i) ){	// there are invalid characters!}

4) Do a check, as in one of my previous posts, to see if the field is a phone number and validate specifically for that field.5) Do a final check to make sure that they didn't just enter " " (remember that all multiple spaces would have been converted to a single space in step 2):

if(text == " "){	// it is just a single space!}

Then, if it passed all those steps, it would be valid. Does that make sense?

Link to comment
Share on other sites

Cheers for the help jesh, and sorry I did'nt get back sooner with a thankyou for the help.I've sort of relented at the moment with this problem, i think i was trying too hard to make the coding shorter and fancier, but in fact became more complex.Thanks again for the help.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...