• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 46
  • Last Modified:

trim(), match() functions for validation

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
Darius
Asked:
Darius
  • 6
  • 4
  • 2
5 Solutions
 
Julian HansenCommented:
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
 
Kim WalkerWeb Programmer/TechnicianCommented:
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
 
Kim WalkerWeb Programmer/TechnicianCommented:
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
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
DariusAuthor Commented:
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
 
Kim WalkerWeb Programmer/TechnicianCommented:
Try:
var invoiceId_1 = invoiceId.replace(/ /g,"");

Open in new window

1
 
Kim WalkerWeb Programmer/TechnicianCommented:
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
 
DariusAuthor Commented:
Perfect! Works

Kim,
 you mentioned Regex
      What is difference between these expression:
(/0+([\w\-]+)/)
(/[^a-zA-Z\d-]/)
0
 
Kim WalkerWeb Programmer/TechnicianCommented:
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
 
Kim WalkerWeb Programmer/TechnicianCommented:
/[^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
 
DariusAuthor Commented:
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
 
Julian HansenCommented:
Sidebar
/0+([\w\-]+)/
Assumes string starts with a 0 if the string does not always start with a 0 then
/0*([\w\-]+)/
1
 
DariusAuthor Commented:
Tank you Julian
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now