How to define variable length of string in XSD template?

The XML input tag must be validated for a template that looks like this:

type : positive int / decimal
minimum length is 0
max length is 12(before decimal point)
fraction digits are optional if exist then precision must be 2.

      

This means that both a positive integer and decimal numbers (two-digit precision) are allowed.

therefore valid values ​​could be like this:

  • NULL
  • 0
  • 0.00
  • 1234567890
  • 123456789012
  • +123456789012.12

Invalid values:

  • 0.000
  • 1234567890123 (13 digits - invalid)

The sample I created:

<xs:pattern value="|([0-9]){12}|([0-9]){12}[.][0-9][0-9]"/>

      

The problem with this pattern is that it doesn't allow a number with a string length less than 12, it says "1234567890" is an invalid value where it should be allowed!

+2


a source to share


2 answers


A regex pattern \d{0,12}(\.\d{2})?

should do the trick.

A brief description of the template:

\d

is short for [0-9]

. \d{0,12}

indicates what \d

should happen 0 to 12 times. He is greedy, so he will try to match as many as he can to 12.



\.\d{2}

represents a point followed by exactly two digits.

?

indicates that the previous element can occur 0 or 1 times. The parentheses around are (\.\d{2})

necessary because without them ?

will only apply to\d{2}

+3


a source


But the above would allow:



.00

as valid input. Perhaps something like: (|\d{1,12}(\.\d{2})?)

to allow zero or at least one digit would be better.

+1


a source







All Articles