Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | Form | Q1710 [ previous next ]

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

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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.