最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - JavaScript Regular Expression Validation - Stack Overflow

programmeradmin1浏览0评论


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!!!


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!!!

Share Improve this question asked Aug 14, 2015 at 7:54 AisRussAisRuss 2694 gold badges8 silver badges16 bronze badges 1
  • /^[a-zA-Z]+\/[a-zA-Z]+\/[a-zA-Z]+$/ will evaluate it for you – user1496463 Commented Aug 14, 2015 at 8:01
Add a comment  | 

6 Answers 6

Reset to default 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`

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

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

or

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

This should do it

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

In javascript

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

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");
  }
}

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.

发布评论

评论列表(0)

  1. 暂无评论