Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1710 How do I ensure that a form field contains a .gov domain (whether that be .gov, .gov.uk etc)?

You are here: irt.org | FAQ | JavaScript | Form | Q1710 [ previous next ]

With the following:

<html>

<head>

<script language="JavaScript"><!---
function validate(value) {
  if (value.indexOf('.gov') < 0) {
    alert('Please supply an appropriate domain');
    return false;
  }
  return true;
}
//--></script>

</head>

<body>

<form onsubmit="return validate(this.domain.value)">
<input type="text" name="domain">
<input type="submit" value="Submit">
</form>

</body>

</html>

However, a much more robust validation can be performed with Regular Expressions:

<html>

<head>

<script language="JavaScript"><!---
var domain = /^w+([\.\-]\w+)*\.gov(\.[A-Za-z][A-Za-z])*$/;

function validate(value) {
  if (!domain.test(value)) {
    alert('Please supply an appropriate domain');
    return false;
  }
  return true;
}
//--></script>

</head>

<body>

<form onsubmit="return validate(this.domain.value)">
<input type="text" name="domain" value="www.somewhere.gov.uk">
<input type="submit" value="Submit">
</form>

</body>

</html>

©2018 Martin Webb