Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 4 123 ... LastLast
Results 1 to 15 of 52
  1. #1
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Javascript Regular expression help , trying for hours!

    hey guys this is based on a huge uni assignment i have, basically one of the validations mentions " This input device must allow alpha numeric characters, hypen (-), slash ( / ) and allow maximum of 150 characters maximum. I've been working on it for hours and im so close but yet so far, my code is below, cheers

    Code:
        var addressString = document.getElementById('address');
        	addressString = addressString.toString();
        if(addressString.length > 150){
        		alert("Must not be greater then 150");
        		document.getElementById("address").focus();
        
       
        
        }							
        var regEx = new RegExp(/^[a-zA-Z0-9]+$/);
        var addresstest = document.getElementById("address").value;
        if(regEx.test(addresstest));
        else{
    		if(addresstest.length == 0)
    			alert("Please fill in address field");
    		else
    			alert("The Family Name contains characters other than a-z, A-Z and '-'");
    	}
    
    	}

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    I interpret your assignment to mean "must allow only alpha numeric characters, hyphen (-), slash ( / ) and allow maximum of 150 characters maximum. " What about spaces? The simplest approach is to test for the existence of characters which are not allowed.

    if(addresstest.length == 0) is inadequate as a single space will return true. I suggest a minimum of 5 characters in an address. Personally I would allow commas and full stops in the address as well. Is the 150-character address to be input as a single line in a textbox? It is more usual to have separate fields for street, city, state, zipcode. Then a mistype in one field does not require the whole address to be entered again.

    Note that whatever your regex is, that does not prevent the user from entering absurd rubbish. xYz6---Tfk So in reality the test is not very useful.


    Code:
    <script type = "text/javascript">
    
    var addressString = document.getElementById('address').value;
    // a form field value is already a string
    if ( (addressString.length < 5) || (addressString.length > 150) || (/[^a-z0-9\s\-\/]/gi.test(addressString)) ){  // only allow letters numbers spaces hyphens forward slash
    alert ("Invalid address - please re-enter it");  // Better to tell the user why the entered field is invalid
    document.getElementById('address').value = "";  // clear the field
    document.getElementById('address').focus();  // refocus on it
    }
    
    else {
    alert ("OK");
    }
    </script>
    You could refine/improve this by stripping out leading and trailing spaces, and replacing multiple spaces by one space.

    Code:
    x = x.replace(/^\s+|\s+$/g,"");  // the g switch is essential!!
    x = x.replace(/\s{2,}/g," ");  // Replace multiple spaces with one space
    Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems." — Jamie Zawinski.

    You can test your regular expressions at: http://www.claughton.clara.net/regextester.html
    Last edited by Philip M; 04-28-2013 at 10:29 AM. Reason: Typos

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Sorry about that, didn't quite explain thorough enough ! yes your absoulately right. Spaces, commas but must be alpha numeric and able to contain hyphens and slashes, i honestly didnt know date from a form is of string type ?

  • #4
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Also could u be kind enough to explain the regular expression by each symbol used, im still trying to get my head around the regex's

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by Johnny87auxsm View Post
    Sorry about that, didn't quite explain thorough enough ! yes your absoulately right. Spaces, commas but must be alpha numeric and able to contain hyphens and slashes, i honestly didnt know date from a form is of string type ?
    A form field value is always a string, so a numeric input must be converted to a number by one of several methods before arithmetic calculations are perfomed on it. If you are lucky Javascript might do the type conversion for you. If not, 1+2 will evaluate to 12, not 3. Always convert numeric strings to numbers explicity.

    Note that a form field value can never be null - only "" (blank).

    [^a-z0-9\s\-\/]/gi

    Within the character class (square brackets), not (^) a letter a-z, a number 0-9, a space, a hyphen or a slash, the g switch meaning global (in fact not strictly required here as as single invalid character is enough to return true), the i switch means ignore case. The \ symbol is the escape character which causes \s to mean a space and not a literal s.

    Note that the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\), the caret (^) and the hyphen (-). You can avoid the need to escape the hyphen in that situation by placing it last immediately before the ]. In fact I usually play safe and escape all the special characters in a character class - the regex still works fine. I could have written it (/[^a-z0-9 /-]/gi.test(addressString))
    Last edited by Philip M; 04-28-2013 at 10:49 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    How would i go about doing this
    "Must be a valid date in the format dd/mm/yyyy and between 2000 and 2004 ? Have to use the document get element by ID as it's required..

  • #7
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I know i need IF statements basically something like 2000<= or greater => 2004.. I just can't put the dam thing in code.. baffled!

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by Johnny87auxsm View Post
    How would i go about doing this
    "Must be a valid date in the format dd/mm/yyyy and between 2000 and 2004 ? Have to use the document get element by ID as it's required..
    What do you mean by a valid date? 31st February is not a valid date.

    Code:
    var d = "01/01/2009";
    var ds = d.split("/");
    if ((ds[2] <2000) || (ds[2] > 2004)) {
    alert ("Year not in range");
    }
    Use the search feature of this forum for a script to check for a valid date (not 56th Febtember or whatever).
    Last edited by Philip M; 04-28-2013 at 11:01 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #9
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Basically the date generated will be between year 2000 and 2004 is what it's asking..

  • #10
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I'm doing a new validation this code i did 10 minutes ago works for phone numbers like this (99)99999999 but how can i change the expression to work with numbers similar but like this (999)9999999 total of 10 numbers..

  • #11
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Johnny87auxsm View Post
    I'm doing a new validation this code i did 10 minutes ago works for phone numbers like this (99)99999999 but how can i change the expression to work with numbers similar but like this (999)9999999 total of 10 numbers..
    Code:
    	{
    
    		var phoneRegAus = new RegExp(/^[(][0-9]{2}[)][0-9]{8}$/);
    		if(phoneRegAus.test(document.getElementById("workphone").value)); 
    		else
    			alert("Your Work Telephone number is invalid: needs to conform to (99)99999999");
    		if(phoneRegAus.test(document.getElementById("homephone").value));
    		else
    			alert("Your Home number is invalid: needs to conform to (99)99999999");
    		if(phoneRegAus.test(document.getElementById("mobile").value));
    		else
    			alert("Your Mobile number is invalid: needs to conform to (99)99999999");
    	}
    	
    
    
    
    	}

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    The change required ought to be obvious.

    But it would be best to strip all non-digits from the phone number and then re-format the 10 digits with the brackets positioned as you desire.

    Please do not abuse this forum by asking us to do all your homework for you. You are entitled to expect some help, but as a student you should not take your pitcher too often to this well. Especially as you seem rather inclined to take the help for granted.

    Code:
    var please = false;
    var thanks = false;
    if (!please && !thanks) {
    var interestLost = true;
    var moreHelp = 0;
    }
    Last edited by Philip M; 04-28-2013 at 01:45 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #13
    Regular Coder
    Join Date
    Apr 2013
    Posts
    112
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks for your help, i've done over 10 validations today just stuck on the much harder ones..

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,986
    Thanks
    79
    Thanked 4,432 Times in 4,397 Posts
    For phone numbers, which might be "1234567890" or "(123) 456-7890" or "123.456.7890" or or or or...

    The solution I (and many others) use is simple: Zap all the non-digit characters and then see if you have string of length 10. And then, if you wish, reformat the numbers.

    Example:
    Code:
    <form id="myForm">
    <input name="phone" />
    ...
    </form>
    
    <script type="text/javascript">
    var form = document.getElementById("myForm");
    form.onsubmit = validateForm;
    
    function validateForm( )
    {
        // validate phone number:
        var ph = form.phone.value.replace(/[^\d]/g,""); // zap all non digits
        if ( ph.length != 10 )
        {
            form.phone.value = "invalid";
            return false;
        }
        form.phone.value = "(" + ph.substr(0,3) + ") " + ph.substr(3,3) + "-" + ph.substr(6);
        ... other validations ...
    
       ... if all is okay: 
       return true;
    }
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,986
    Thanks
    79
    Thanked 4,432 Times in 4,397 Posts
    For the date validation, you might do something like this:
    Code:
    <form id="myForm">
    <input name="myDate" />
    ...
    </form>
    
    <script type="text/javascript">
    var form = document.getElementById("myForm");
    form.onsubmit = validateForm;
    
    function validateForm( )
    {
        var dt = form.myDate.value;
        var dtre = /^\d\d?\/\d\d?\/\d{4}$/;
        if ( ! dtre.test(dt) )
        {
            form.myDate.value = "invalid";
            return false;
        }
        var parts = dt.split("/");
        var check = new Date(parts[2],parts[0]-1,parts[1]);
        if (    check.getMonth() != Number(parts[0])
             || check.getYear() < 2000 || check.getYear() > 2004 )
        {
            form.myDate.value = "invalid";
            return false;
        }
        ... other validation...
    
        return true;
    }
    </script>
    Note that checking to see if the month from the new Date() is the same as the first digit(s) in the mm/dd/yyyy format is sufficient to check if the mm is in the range 1 through 12 *AND* if the dd is in the correct range for the given mm.

    That's because, just as an example, JavaScript convertsnew Date(2003,3,31) *automatically* to 5/1/2003. And it converts new Date(2001,12,33) to 2/2/2002. And so on. It accepts any numbers for mm and dd and then "corrects" them to make sense of the date. (Remember that month numbers go from 0 to 11 in JS.)
    Last edited by Old Pedant; 04-28-2013 at 10:17 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  
    Page 1 of 4 123 ... LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •