JavaScript to verify that form input contains at least 1 letter and at least 1 number


Enter whatever you want in the field and click "Submit". If you enter at least one letter and one number, the function will tell you your input is "Valid". If not, it will tell you "Invalid".

The method used below starts with 2 flags both set to "false". One flag for "letter" and one flag for "number". As it looks through each character of input if it determines that a character is a letter, it sets that flag to true. Same for if the character is a number. By the end of the routine, every character has been examined.

Field 1:
Submit

<form name="form1" method="post" action="">

Field 1: <input type="text" id="field1" name="textfield">

<br /><a href="javascript:Validator();">Submit</a>

</form>

<script language="javascript" type="text/javascript">

  function Validator(){

  var fieldContainsANumber = false;

  var fieldContainsALetter = false;

  var temp;

  var blankValue = false;

    if (document.form1.field1.value.length > 0) {

      for (i=0; i < document.form1.field1.value.length; i++){

        temp = document.form1.field1.value.charAt(i);

        if(/[0-9]/.test(temp)){

          var fieldContainsANumber = true;

        }

        if(/[A-Za-z]/.test(temp)){

          var fieldContainsALetter = true;

        }

      }

    }

    else{

      alert('Please enter a value for field 1');

      blankValue = true;

    }

    if (!(blankValue) && (fieldContainsANumber && fieldContainsALetter)){

      alert('Valid');

      //document.forms['form1'].submit();

    }

    else{

    alert('Invalid');

    }

  }

  </script>