Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Possible to make regex that doesn't allow https in hostname?

I am using validate, and need to validate a host, and would like to have it fail, if http://, https:// or it is ending with / as in https://google.com/. It should fail if it is anything but of the form google.com.

Does anyone know how to do that?

const Schema = require('validate');

const p_schema = new Schema({
  Host: {
    type: String,
    match: /???/,
    required: true
  },
});
let p = {
    Host: 'https://google.com/'
}

const errors = p_schema.validate(p)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want to check if your string contains a valid hostname, and you want your validation to fail if your string contains extraneous junk.

For that, use the npm is-valid-hostname package, and avoid creating your own regex for the purpose. There are lots of weird edge cases in hostnames, so you may as well use fully-debugged code rather than taking on the testing burden of writing your own regex.

const isValidHostname = require('is-valid-hostname')

isValidHostname('https://google.com/') // false
isValidHostname('google.com:443')      // false
isValidHostname('google.com')          // true
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading