0

I have a string that should be validated to be in the form of something like "Readdata.v5". What I do in my code, is I split the string based on the . (I check to make sure there is exactly one . in the string, so all other cases are handled). I want to validate it so that the first part of the string follows the format of a phrase, followed by any character to the period. The second part should start with the char v and then be followed by any number. This is the regex I have so far:

console.log("first field validation: " + splitArray[0].match(/^\"(Create|Read|Update|Delete)[a-zA-Z]*.$/));
console.log("Second field validation: " + splitArray[1].match(/^.vd+\"$/));

However, it doesn't seem like my regex is working. Did I make a mistake? The values in the array are correct, and split the values correctly (the quotations are a part of the string).

9
  • 2
    Digit pattern is \d, not d. Commented Dec 10, 2018 at 17:28
  • 1
    can't you do it with single regex. i don't understand need of splitting Commented Dec 10, 2018 at 17:29
  • @CodeManiac I suppose, regex is something I'm not the best at. Commented Dec 10, 2018 at 17:30
  • @user3334871 you can do it with single regex itself. well if you some more example i can write one. Commented Dec 10, 2018 at 17:31
  • 1
    When you split the data, then . character shouldn't be included in your regex. Commented Dec 10, 2018 at 17:31

2 Answers 2

2

You can use this

^"(Create|Read|Update|Delete)[a-zA-Z]*\.v\d+"$

Explanation

  • ^ - Anchor to start of string.
  • (Create|Read|Update|Delete) - Will match Create or Read or Update or Delete.
  • [a-zA-Z]* - Will match any character zero or more time.
  • ``.- will match.`.
  • v\d+ - Will match v followed by one or more digits.
  • $ - End of string.

Demo

Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't you include the quotes around "Readdata.v5"?
@rv7 i thought those were used just to string.
Actually, the quotes are a part of the string :) . I just put ^\"(Create|Read|Update|Delete)[a-zA-Z]*\.v\d+\"$
@user3334871 my bad i thought that was just representation of string.updated my answer.
2

If you want to validate that there is a "." in the chain, you can do this:

var stringToValidate = 'jon.foo';

if(!!stringToValidate.indexOf('.')){
 console.log('true')
}

the conditional is evaluated a true or false

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.