Jogn Smit
Jogn Smit

Reputation: 87

How to validate for letters only in this specific script - javascript

I would need a little help of you today, i'm wondering how can i validate my script for letters only on first 2 inputs?

I'm using javascript to validate my form below: I have managed to validate for email though and zip (numbers only)...

<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
function checkForEmail()
{

   var emailID = document.myForm.EMail.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 )) 
   {
       alert("Alert")
       document.myForm.EMail.focus() ;
       return false;
   }
   return( true );
}

function validate()
{
   if( document.myForm.Name.value == "" )
   {
     alert( "Alert" );
     document.myForm.Name.focus() ;
     return false;
   }
   if( document.myForm.Surname.value == "" )
   {
     alert( "Alert" );
     document.myForm.Surname.focus() ;
     return false;
   }
   if( document.myForm.EMail.value == "" )
   {
     alert( "Alert" );
     document.myForm.EMail.focus() ;
     return false;
   }else{
     var ret = checkForEmail();
     if( ret == false )
     {
          return false;
     }
   }
   if( document.myForm.zip.value == "" ||
           isNaN( document.myForm.zip.value ) ||
           document.myForm.zip.value.length != 13 )
   {
     alert( "Alert" );
     document.myForm.zip.focus() ;
     return false;
   }
   return( true );
}
//-->
</script>
</head>
<body>
 <form action="/cgi-bin/test.cgi" name="myForm"  onsubmit="return(validate());">
 <table cellspacing="2" cellpadding="2" border="1">
 <tr>
   <td align="right">Name</td>
   <td><input type="text" name="Name" /></td>
 </tr>
  <tr>
   <td align="right">Surname</td>
   <td><input type="text" name="Surname" /></td>
 </tr>
 <tr>
   <td align="right">EMail</td>
   <td><input type="text" name="EMail" /></td>
 </tr>
 <tr>
   <td align="right">zip</td>
   <td><input type="text" name="zip" /></td>
 </tr>
 <tr>
 <td align="right"></td>
 <td><input type="submit" value="Submit" /></td>
 </tr>
 </table>
 </form>
 </body>
 </html>

Upvotes: 0

Views: 173

Answers (1)

RobG
RobG

Reputation: 147523

how can i validate my script for letters only on first 2 inputs

// Check s contains at least one letter and is only letters
function checkLettersOnly(s) {
  return /^[a-z]+$/i.test(s);
}

if (!checkLettersOnly(document.myForm.Name.value)) {
  // not letters only
}

Upvotes: 1

Related Questions