Solved

trim(), match() functions for validation

Posted on 2016-10-05
12
32 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 55

Assisted Solution

by:Julian Hansen
Julian Hansen earned 100 total points
ID: 41830401
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 22

Assisted Solution

by:Kim Walker
Kim Walker earned 400 total points
ID: 41830413
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 22

Accepted Solution

by:
Kim Walker earned 400 total points
ID: 41830461
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:Darius
ID: 41830654
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 22

Assisted Solution

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

Open in new window

1
 
LVL 22

Expert Comment

by:Kim Walker
ID: 41830713
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
 

Author Comment

by:Darius
ID: 41830730
Perfect! Works

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

Assisted Solution

by:Kim Walker
Kim Walker earned 400 total points
ID: 41830738
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 22

Expert Comment

by:Kim Walker
ID: 41830757
/[^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
ID: 41830823
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 55

Expert Comment

by:Julian Hansen
ID: 41831214
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
ID: 41831295
Tank you Julian
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses how to create an extensible mechanism for linked drop downs.
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…

828 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