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

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

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

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

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>

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.