Balkar Kalsi Balkar Kalsi - 1 year ago 41
Javascript Question

Basic Input field Validation in Javascript

I am very new to JavaScript, so I started learning from Forms. Kindly have a look at code and suggest.

I am trying to validate the first field only, it must contain string, but not numeric and also should not contain alpha numeric characters. But if I enter alpha numeric characters, it does not show the alert message window. Kindly advise.

function checkFields()
var tname = document.getElementById("t0_name").value;
var texpense = document.getElementById("t1_expense").value;
var tdate = document.getElementById("t2_date").value;
var tamt = document.getElementById("t3_amt").value;
var tstatus = document.getElementById("t4_status").value;
var temail = document.getElementById("t5_email").value;
var alphanumeric = /[^a-zA-Z0-9]/;
if (tname == null || tname == "") {
document.getElementById("t0_name").style.border = "1px solid black";
alert('should not be blank');
} else if (!isNaN(tname)) {
alert('Should not be Numeric');
document.getElementById("t0_name").style.border = "1px solid red";
} else if (/[^a-zA-Z0-9]/.test(tname)) {
alert('Input is not alphanumeric');



You can use the following regex to check for only characters and not alphanumeric i.e. characters and numbers.

/^[a-zA-Z]+$/.test('Abc') // true

/^[a-zA-Z]+$/.test('a1') // false

In your regex you've specified numbers from 0-9 so that's why it returns true on alphanumeric.

You can also use \D i.e. a non-digit


The + sign before the $ is for one or more characters.