Home > OS >  Validating a contact form using javascript
Validating a contact form using javascript

Time:04-12

I'm trying to validate this form to require an email address using JavaScript. I think I'm close to it but I can't figure out what I am doing wrong. Any help would be much appreciated

HTML

<div >
        <form name="theForm" action="/action_page.php" onclick="ValidateEmail(document.theForm.email)>
          <label  for="fname">Name</label>
          <input type="text" id="fname" name="firstname" placeholder="Your name.." minlength="2" required>
      
          <label   for="lname">Email</label>
          <input type="text" id="mail" name="email" placeholder="Email..">
      
      
          <label   for="subject">Subject...</label> 
          <textarea id="subject" name="subject" placeholder="Write something.." style="height:200px" minlength="25" required></textarea>
      
          <input type="submit" value="Send">
        </form>
      </div>

JavaScript

function ValidateEmail(mail) 
{
 if (/^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,3}) $/.test(myForm.emailAddr.value))
  {
    return (true)
  }
    alert("You have entered an invalid email address!")
    return (false)
}

CodePudding user response:

This should work

function ValidateEmail(myForm) {
  if (/^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,3}) $/.test(myForm[1].value)) {
    return (true)
  }
  alert("You have entered an invalid email address!")
  return (false)
}
<div >
  <form name="theForm" action="/action_page.php" onclick="ValidateEmail(this)">
    <label  for="fname">Name</label>
    <input type="text " id="fname " name="firstname " placeholder="Your name.. " minlength="2 " required>

    <label  for="lname ">Email</label>
    <input type="text " id="mail " name="email " placeholder="Email.. ">


    <label  for="subject ">Subject...</label>
    <textarea id="subject " name="subject " placeholder="Write something.. " style="height:200px " minlength="25 " required></textarea>

    <input type="submit " value="Send ">
  </form>
</div>

CodePudding user response:

Use the onchange function like this.

<label   for="email">Email</label>
<input type="text" id="mail" name="email" placeholder="Email.." onchange="ValidateEmail(this.value)">
  • Related