Chris Chris - 6 months ago 3
Javascript Question

Check fields contain data and that one is a number

New to javascript but I am trying to check if three fields (1) contain some data and that (2) the third one contains any numbers. The third one is a telephone # field. I realize dashes would be involved. And that the form could validate if a user entered only one number or a number and some text. But I'm starting small. Any help would be great.

function validate(){
if ((document.myForm.fname.value=="") || (document.myForm.lname.value=="")
|| (document.myForm.telenumber.value=="")){
alert("You must fill in all of the required fields!")
return false
return true

<form name="myForm" onsubmit="return validate()">
<label for="fname">First name</label>
<input type="text" id="fname" name="firstname"><BR>
<label for="lname">Last name</label>
<input type="text" id="lname" name="lastname"><BR>
<label for="tele">Telephone number</label>
<input type="text" id="tele" name="telenumber">

<input type='submit' value='Submit' /><br />


I would use the typeof function to check if fname and lname are strings plus a regular expression to check if the phone number format is valid.

Working code example:

  function validate(e) {

    var fname = document.getElementById('fname').value,
        lname = document.getElementById('lname').value,
        phone = document.getElementById('tele').value;
     //regex example for phone number format
     var regex = new RegExp('^((([0-9]{3}))|([0-9]{3}))[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4}$');
    if(typeof fname === 'string' && typeof lname === 'string' && regex.test(phone))
      console.log('Ok. valid user data');
      alert('Invalid user data!');

  // Event listner for form submission
  document.getElementById('myForm').addEventListener('submit', validate);

<form name="myForm">
    <label for="fname">First name</label>
    <input type="text" id="fname" name="firstname">
    <label for="lname">Last name</label>
    <input type="text" id="lname" name="lastname">
    <label for="tele">Telephone number</label>
    <input type="text" id="tele" name="telenumber">

    <input type='submit' value='Submit' />

Additional Note:

I'm checking the form controls to be string with typeof for more code clarity, but it is redundant as the form control are always type string.

So if you want the validation condition can be just if(regex.test(phone))