Solved

trim(), match() functions for validation

Posted on 2016-10-05
12
18 Views
Last Modified: 2016-10-06
Guys,
I need to solve an issue with validation. I have code below and I need to validate
entered value.
Accepted values is alpha, numeric or '-'(hyphen) characters.


input:                     '  00ab-12cd34000   '
expected result:  'ab-12cd34000'                  // => should not give a warning.

input:                    '  00ab-12cd3_&*%^£$4000   '
expected result:  'ab-12cd3_&*%^£$4000'  // => warning - Invoice ID have invalid characters


var invoiceId;
        invoiceId = document.getElementById("txtId").value.trim(); // trailing and leading white-spaces
        var invId = invoiceId.match(/0+([\w\-]+)/); // alphanumeric and  '-' (hyphen) characters only
        var invMatch = invoiceId.match(/0*(.*)/); // any characters

// If no value or value is white-space
        if (invoiceId == "") {
            warn = "!" + "Please, enter the Invoice ID.\n";
            document.body.style.cursor = 'default';
            document.getElementById("btnSend").onclick = '';
             }  

// if entered value have not (alpha, numeric or '-'(hyphen)) characters => gives warning
        else if (invId != invMatch) {
            warn = "!" + "Invoice ID has invalid characters.\n";
            document.body.style.cursor = 'default';
            document.getElementById("btnSend").onclick = '';
        }
. . .

Open in new window


Thank you!
0
Comment
Question by:Darius
  • 6
  • 4
  • 2
12 Comments
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 100 total points
Comment Utility
Why do you need to distinguish between the tests - look for a valid /0+([\w\-]+)/ and if not found it is invalid.
var invId = invoiceId.match(/0+([\w\-]+)/); 
if (!invId) {
  alert("Please enter a valid invoiceId");
}

Open in new window

Why the need to complicate it by checking for specific cases of invalidity?
1
 
LVL 21

Assisted Solution

by:Kim Walker
Kim Walker earned 400 total points
Comment Utility
If you want to check for the existence of a character that is NOT alphanumeric or a dash, you would search for a match of [^a-zA-Z\d-].
invoice.match(/[^a-zA-Z\d-]/);

Open in new window

The match function returns the valid matches. It is unconcerned with characters that do not match. If the match function returns false, that simply means that no matches were found, but does not indicate that other characters exist. If valid characters exist amid invalid characters, match will return the valid matches the same as if the invalid characters were removed. You are looking for characters that do not match, not the inverse of characters that do match.
0
 
LVL 21

Accepted Solution

by:
Kim Walker earned 400 total points
Comment Utility
Since match will find the valid string in both of the samples you provided, if you want to make sure the string is valid and not invalid, you could compare the length of the valid match with the original string. By removing the parentheses from the regex, you reduce the number of matches in the second string to one.
var invoiceId = "  00ab-12cd3_&*%^£$4000  ".trim(); // trailing and leading white-spaces
var invId = invoiceId.match(/0+[\w-]+/); // alphanumeric and  '-' (hyphen) characters only
var invalidMatch = invId[0] !== invoiceId;  // returns true if invalid

Open in new window

This code is for the second sample you provided in your question. The variable invalidMatch will be false (not invalid) for the first example and true (yes it is invalid) for the second example.

There is still a flaw in this regex, however. The underscore is considered a word character. So the presence of an underscore would not be detected as invalid. If you want only alphanumeric characters and the dash, you would need to match /0+[a-zA-Z\d-]+/ or /0+[a-z\d-]+/i (case insensitive).
0
 

Author Comment

by:Darius
Comment Utility
Kim, Julian Thank you! Solved

var invoiceId;
var matchInvId;
invoiceId = document.getElementById("txtMessageId").value.trim();
matchInvId = invoiceId.match(/0+([\w\-]+)/);

     if (invoiceId == "") {
            alert ("Please enter the Invoice ID");
        }
     else if (!matchInvId) {
            alert ("Please enter a valid Invoice ID");
        }
     else if (matchInvId[1].toString().length > 10) {
            alert ("Invoice ID has more then 10 characters.");
        }
. . .

But!!!  I have more questions...  :)
I using trim function above to remove leading trailing white-spaces
What function stand for to remove white-space inside string?
input:                     '  00 ab      - 1  2c d 3 400 0   '

These does not working for me...
        var invoiceId_1 = invoiceId.replace(" ", "");
        var invoiceId_2 = invoiceId.replace(' ', '');
        var invoiceId_3 = invoiceId.toString().replace(" ", "");
        var invoiceId_4 = invoiceId.toString().replace(' ', '');
0
 
LVL 21

Assisted Solution

by:Kim Walker
Kim Walker earned 400 total points
Comment Utility
Try:
var invoiceId_1 = invoiceId.replace(/ /g,"");

Open in new window

1
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
By the way, the following string would NOT produce an error with this routine.
"  00 ab      _ 1  2c d 3 4 &  "

Open in new window

1
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Darius
Comment Utility
Perfect! Works

Kim,
 you mentioned Regex
      What is difference between these expression:
(/0+([\w\-]+)/)
(/[^a-zA-Z\d-]/)
0
 
LVL 21

Assisted Solution

by:Kim Walker
Kim Walker earned 400 total points
Comment Utility
Neither does your second example.
"  00ab-12cd3_&*%^£$4000   "

Open in new window

Match ignores all the characters after the underscore so matchInvId[1] = ab-12cd3_ which is only 9 characters.
1
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
/[^a-zA-Z\d-]/ looks for any character that is NOT alpha (a-zA-Z) and NOT numeric (\d) and NOT a dash (-).

/0+([\w\-]+)/ looks for a string that begins with 1 or more zeros (0+) followed by one or more word characters or dashes ([\w\-]+). The one or more word characters or dashes is isolated in parentheses and produces a separate match in the match array.
0
 

Author Comment

by:Darius
Comment Utility
updated code!
       Thanks Kim

var invoiceId;
var matchInvId;
invoiceId = document.getElementById("txtMessageId").value.replace(/ /g, "");
matchInvId = invoiceId.match(/0+([\w\-]+)/); 

     if (invoiceId == "") {
            alert ("Please enter the Invoice ID");
        }
     else if (matchInvId[0] !== invoiceId) {
            alert ("Please enter a valid Invoice ID");
        }
     else if (matchInvId[1].toString().length > 10) {
            alert ("Invoice ID has more then 10 characters.");
        }
. . .

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Sidebar
/0+([\w\-]+)/
Assumes string starts with a 0 if the string does not always start with a 0 then
/0*([\w\-]+)/
1
 

Author Comment

by:Darius
Comment Utility
Tank you Julian
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now