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

Q1320 How can I validate a text input field so that only letters are taken and no numbers?

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

The following will inhibit non alphabetic input into any form field on the current page:

<html>

<head>
<script language="JavaScript"><!--
function validate(e) {
    if (navigator.appName == 'Microsoft Internet Explorer')
        key = window.event.keyCode;
    else
        key = e.which;

    if (key < 65 || key > 122 || (key > 90 && key < 97))
        return false;
    return true;
}

if (navigator.appName == 'Netscape') {
    window.captureEvents(Event.KEYPRESS);
    window.onKeyPress = validate;
}
//--></script>

</head>

<body onKeyPress="validate()">

<form>
<input type="text">
</form>

</body>

</html>

The following version allows you to inhibit non alphabetic input into individual form fields:

<html>

<head>
<script language="JavaScript"><!--
var inhibit = false;

function validate(e) {
    if (!inhibit)
        return true;

    if (navigator.appName == 'Microsoft Internet Explorer')
        key = window.event.keyCode;
    else
        key = e.which;

    if (key < 65 || key > 122 || (key > 90 && key < 97))
        return false;
    return true;
}

if (navigator.appName == 'Netscape') {
    window.captureEvents(Event.KEYPRESS);
    window.onKeyPress = validate;
}
//--></script>

</head>

<body onKeyPress="validate()">

<form>
<input type="text" onFocus="inhibit=true">
<input type="text" onFocus="inhibit=false">
</form>

</body>

</html>

©2018 Martin Webb