Click here to Skip to main content
15,039,714 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to validate textbox(Bank Challan number) to enter alphanumeric hyphen and slash only.
Consecutive hyphen or slash not allowed.
Like _/ and /_ and _ _ and // and whitespace not allowed

What I have tried:

JavaScript
re=/^[0-9a-zA-Z/ -]+$/;

                if( $('#<%=txt.ClientID%>').val().match(re))
                {
                    alert("valid");
                    
                }
                else {
  alert("not valid");
                }
Posted
Updated 30-Mar-16 0:36am
v3

1 solution

To do the testing against the regex, you can use the test method on RegExp.
RegExp.prototype.test() - JavaScript | MDN[^]
JavaScript
if (re.test($('#<%=txt.ClientID%>').val()))

It's not at all easy to add the rule against consecutive chars in the regex which you already have. Therefore, I propose that you use a second regex: the first regex is to check that it only contains alphanumeric chars, slashes, hyphens and whitespace (you already have this regex), the second regex is to check if there are consecutive slashes and/or hyphens. This regex would look like this:
var re_consecutive_chars = /[/-]{2,}/;

If the textbox value matches this regex, you know that it has consecutive slashes, consecutive hyphens, a slash followed by a hyphen or a hyphen followed by a slash.


I'd also like to say this: I don't know whether you will use the textbox value on the server, but if you do, don't forget to do validation on the server as well. Client-side validation can easily be turned off by users. Server-side validation cannot.
   
v4
Comments
Member 7909353 30-Mar-16 5:57am
   
Yes I will use textbox value on the server.
And tell pattern now.
Thomas Daniels 30-Mar-16 5:58am
   
The regular expression, which you already had, works fine.
Thomas Daniels 30-Mar-16 5:59am
   
Oh, I missed that you couldn't have a consecutive hyphen and slash, sorry. Will look for a pattern for this.
Thomas Daniels 30-Mar-16 6:04am
   
I edited my answer.
Member 7909353 30-Mar-16 6:36am
   
I want to validate Bank Challan number in javascript
Thomas Daniels 30-Mar-16 6:49am
   
I have no idea how that would look like.
Member 7909353 30-Mar-16 7:13am
   
Suppose Alphanumeric, hyphen and forward slash are valid
Thomas Daniels 30-Mar-16 8:17am
   
They are valid in the current regex. What problem are you facing exactly?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900