xsdxsd-validation

Add pattern to anyURI data type in xsd


How can I guarantee that the url element starts with "http://"?

<xs:element name="url" type="xs:anyURI"/>

Solution

  • You can add a xs:restriction for a Regular Expression using xs:pattern:

    <xs:element name="url">
        <xs:simpleType>
            <xs:restriction base="xs:anyURI">
                <xs:pattern value="http://.+" />
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    

    This will match to anything that starts with http://. It will match:

    http://www.stackoverflow.com
    http://somethingsomethingsomething
    http://123456789!!!!!
    http://0
    

    It will not match https URLs:

    https://github.com
    

    If you want to match https as well you can change the pattern to

    https?://.+
    

    which means that the s is allowed and is optional.

    If you want to match only valid URLs then you need to improve it to check for characters, followed by a dot, more characters, a valid domain suffix, etc. If you search for URL validation via regex you will find several examples. You can also try this resource. And to experiment with Regex, Regex 101 is a great resource.

    Pattern matching in XSD has some restrictions. Check this SO question/answer which discusses that.