5


I'm attempting to validate a field name to match a certain format in JavaScript using Regular Expressions.

I need the string inputted to resemble this:
word\word\word
So anything inputted can't be blank, and it must be three words seperated by a backslash.

This is the code i'm working with, but i'm not sure if the pattern is the right syntax?!!

    function validateResourceName() {
       //get posted resource name value
       var inputString = document.getElementById("resourceName").value;
       //should be in the word\word\word format
       var pattern=/[a-Z|/\\/|a-Z|/\\/|a-Z\s]/;

       //If the inputString is NOT a match
       if (!pattern.test(inputString)) {
        alert("not a match");
       }
      else
      {
            alert("match");
      }
    }


Any help will be very appreciated!!!

1
  • /^[a-zA-Z]+\/[a-zA-Z]+\/[a-zA-Z]+$/ will evaluate it for you Commented Aug 14, 2015 at 8:01

6 Answers 6

4

Try /^[a-z]+\\[a-z]+\\[a-z]+$/

function validateResourceName() {
  //get posted resource name value
  var inputString = document.getElementById("resourceName").value;
  //should be in the word\word\word format
  var pattern=/^[a-z]+\\[a-z]+\\[a-z]+$/
  //If the inputString is NOT a match
  if (!pattern.test(inputString)) {
    alert("not a match");
  } else {
    alert("match");
  }
}

If you want to allow the word matching to be case insensitive;

`/^[a-z]+\\[a-z]+\\[a-z]+$/i`

If you want to be a bit more broad with what you define as a 'word', and allow it to consist of alphanumeric characters and underscore;

`/^\w+\\\w+\\\w+$/i`
Sign up to request clarification or add additional context in comments.

Comments

3

If by word you mean the English letters a-z in upper or lower case, then:

/^(?:[a-z]+\\){2}[a-z]+$/i

That says:

  • ^ Beginning of string
  • (?:...) Non-capturing group
  • [a-z]+ One or more letters a-z (or A-Z because of the i flag at the end). If you also want to allow some other characters, just add them to the [a-z] after the z. If you want to allow hyphens, add \- to it (you need the backslash, depending on where you put the hyphen, so I just always include it). Note that this is very English-centric, and even in English sometimes people write borrowed words with their non-English letters, such as résumé.
  • \\ Backslash
  • {2} Repeated twice
  • (Then another word)
  • $ End of string

The issues with your expression are:

  • [a-Z] Is invalid because the range is out of order (Z comes before a). If it were valid (or if you wrote [Z-a]), it would matches everything between Z and a, which isn't just a-z and A-Z
  • \\/ Requires a backslash and then a slash
  • | is an alternation (this or that)
  • \s is whitespace

3 Comments

I get Invalid regular expression in Chrome using [a-Z]. Range out of order in character class
@RGraham: I'm glad to hear that. :-) Yeah, it would have to be [Z-a] to get the order right, since Z comes before a. (Some regex engines in other languages just quietly reverse the range for you, I think.)
And of course, Z-a wouldn't match A-Y or b-z. :-)
1

you can just use this \w+\\\w+\\\w+

or

[a-zA-Z]+(\\[a-zA-Z]+){2}

5 Comments

\w does more than what he appears to want (it includes digits and such)
This would include digits and underscores
pls see wiki they clearly mention to match words we should use \w
@raghavendra: What the wiki wants and what the OP wants aren't necessarily the same thing. In particular, underscores aren't part of a "word" in English.
@raghavendra: Well, the OP hasn't weighed in with what they consider a "word," so... (But probably not underscores, to be fair.)
0

This should do it

^\w+\\\w+\\\w+$

In javascript

if (/^\w+\\\w+\\\w+$/.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}

Comments

0

Try this one. See JSFiddle for the code demo.

Regex

/(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g

JavaScript

function validateResourceName(string) {
 var pattern = /(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g;
  if (!pattern.test(string)) {
    alert("not a match");
  } else {
    alert("match");
  }
}

1 Comment

This allows for an empty word: var string = '\\\\';
0

Here I came up with a robust solution where you can find everything in one place. In function, you can find all types of validation in the same method with the proper message.

For JavaScript Users...

function validateInput(input,type,max,min,confirmPassword ='' ){
            input = input.toLocaleString();

            const validateMaxLength = (maxLen) => input.length <= maxLen;
            const validateMinLength = (minLen) => input.length >= minLen;
            const validateNotEmpty = () => input.trim() !== '';

            if( !validateMaxLength(max) ){
                return {status:'error',msg:'String is too long.'};
            }
            else if( !validateMinLength(min))
                return    {status:'error',msg:'String is too short.'};

            else if( !validateNotEmpty() ){
                return   {status:'error',msg:'String can not empty.'};
            }
           else if( type === 'email'){
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if( !emailRegex.test(input) ){
                    return  {status:'error',msg:'Email is not valid.'};;
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'alphanumeric' )
            {
                const alphanumericRegex = /^[a-zA-Z0-9\s]+$/;
                if( !alphanumericRegex.test(input) ){
                    return  {status:'error',msg:'String is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'onlyString' )
            {
                const stringRegex = /^[a-zA-Z\s]+$/;
                if( !stringRegex.test(input) ){
                    return  {status:'error',msg:'Email is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'onlyNumber' )
            {
                const numberRegex = /^[0-9]+$/;
                if( !numberRegex.test(input)  ){
                    return  {status:'error',msg:'Number is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'mobileNumber' )
            {
                const mobileRegex = /^[+\s0-9]+$/;

                if( !mobileRegex.test(input) ){
                    return  {status:'error',msg:'Mobile number is invalid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'alphanumericWithSpecial' )
            {
                const alphanumericSpecialRegex = /^[a-zA-Z0-9!@#$%&*()_+\-=\[\]{};':"\\|,.<>\/?\s]*$/;

                if( !alphanumericSpecialRegex.test(input) ){
                    return  {status:'error',msg:'String is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'webURL' )
            {
                const urlRegex = /^(ftp|http|https):\/\/[^ "]+$/;

                if( !urlRegex.test(input) ){
                    return  {status:'error',msg:'Web url is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'confirmPassword' )
            {
                if (input !== confirmPassword.toString()) {
                    return  {status:'error',msg:'Passwords do not match.'};
                }
                return {status:'success',msg:""};
            }
                return  {status:'error',msg:"Invalid Type"};
        }

Use Case :

 Console.log( validateInput("[email protected]","email",80,10 ) )

For VUE JS :

 methods:{  
      validateInput(input,type,max,min,confirmPassword ='' ){
            input = input.toLocaleString();

            const validateMaxLength = (maxLen) => input.length <= maxLen;
            const validateMinLength = (minLen) => input.length >= minLen;
            const validateNotEmpty = () => input.trim() !== '';

            if( !validateMaxLength(max) ){
                return {status:'error',msg:'String is too long.'};
            }
            else if( !validateMinLength(min))
                return    {status:'error',msg:'String is too short.'};

            else if( !validateNotEmpty() ){
                return   {status:'error',msg:'String can not empty.'};
            }
           else if( type === 'email'){
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if( !emailRegex.test(input) ){
                    return  {status:'error',msg:'Email is not valid.'};;
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'alphanumeric' )
            {
                const alphanumericRegex = /^[a-zA-Z0-9\s]+$/;
                if( !alphanumericRegex.test(input) ){
                    return  {status:'error',msg:'String is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'onlyString' )
            {
                const stringRegex = /^[a-zA-Z\s]+$/;
                if( !stringRegex.test(input) ){
                    return  {status:'error',msg:'Email is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'onlyNumber' )
            {
                const numberRegex = /^[0-9]+$/;
                if( !numberRegex.test(input)  ){
                    return  {status:'error',msg:'Number is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'mobileNumber' )
            {
                const mobileRegex = /^[+\s0-9]+$/;

                if( !mobileRegex.test(input) ){
                    return  {status:'error',msg:'Mobile number is invalid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'alphanumericWithSpecial' )
            {
                const alphanumericSpecialRegex = /^[a-zA-Z0-9!@#$%&*()_+\-=\[\]{};':"\\|,.<>\/?\s]*$/;

                if( !alphanumericSpecialRegex.test(input) ){
                    return  {status:'error',msg:'String is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'webURL' )
            {
                const urlRegex = /^(ftp|http|https):\/\/[^ "]+$/;

                if( !urlRegex.test(input) ){
                    return  {status:'error',msg:'Web url is not valid.'};
                }
                return {status:'success',msg:""};
            }
            else if ( type === 'confirmPassword' )
            {
                if (input !== confirmPassword.toString()) {
                    return  {status:'error',msg:'Passwords do not match.'};
                }
                return {status:'success',msg:""};
            }
                return  {status:'error',msg:"Invalid Type"};
        } ,
    debounceEmailValidation: _.debounce( function (){
          let d =  this.validateInput(this.email,'email',50,10 );
          if( d.status === 'error'){
                this.errors={email:[ d.msg]};
                return
            }
            this.errors={email:[]};
        }, 1000),
  },
 watch:{
        'email':{
            handler(){
                 this.debounceEmailValidation();
            }
        }
     },

debounceMobileValidation using debounce is not mandatory. I used it because there was a need for a program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.