简体   繁体   中英

Form data validation before submission

In this form,i want that when i submit the form it will validate the form and then submitted but here the form is submitted without validating. Whenever i click on submit button, it asks for validation but without validating it is submitted to database. I want onsubmit, it asks for validation and when valid data are inserted then form will submit.

<html>
    <head>
    <title>Ajax Form</title>
    <style>
    .right-align{
        position: absolute;
        right: 70%;
        text-align: left;
    }
    .select_country{
        position: absolute;
        right: 70%;
        width: 160.8;
        height: 22;
    }
    </style>
    <head>
    <body>
        <form name="bhawesh" onsubmit="validate()" method="post" action="formajaxsub.php">
            NAME:  <input type="text" name="name" class="right-align"><br><br>
            FATHER'S NAME:  <input type="text" name="father" class="right-align"><br><br>
            E-MAIL:<input type="text" name="email" class="right-align">  </font><br><br>
            CONTACT:<input type="text" name="contact" class="right-align">  </font><br><br>
            COUNTRY:  
                <select name="country" class="select_country" >
                    <option>--Select--</option>
                    <option name="ind">INDIA</option>   
                    <option name="eng">ENGLAND</option>
                    <option name="chi">CHINA</option>
                    <option name="aus">AUSTRALIA</option>
                </select><br><br>
            <input type="submit" Value="SUBMIT" name="submit">
        </form>
    </body>

    <script>
    function validate()
    {

        var a = document.forms["bhawesh"]["name"].value;
        if (a == "")
        {
            alert("Enter the name");
        }

        var b = document.forms["bhawesh"]["father"].value;
        if (b == "")
        {
            alert("Enter the Father's name");
        }

        var c = document.forms["bhawesh"]["email"].value;
        if (c.indexOf("@")<1 || c.lastIndexOf(".")+2>=c.length || c.indexOf("@")+2>c.lastIndexOf("."))
        {
            alert("The E-Mail is not OK");
        }

        var phone = document.forms["bhawesh"]["contact"].value;
        if(phone.length > 6 && phone.length < 11) 
        {   
        return true;  
        }
        else
        {
            alert("Contact Number is not OK");
        }   


        var e=document.forms["bhawesh"]["country"].value;
        if (e=="")
        {
            alert("Select the country");
        }
    }
    </script>
    </html>

Remove the onsubmit property and attach a submit event handler to process the form before submission.

HTML form:

<form id="bhawesh" name="bhawesh" method="post" action="formajaxsub.php">
  NAME:  <input type="text" name="name" class="right-align" required />
  <br/><br/>
  FATHER'S NAME:  <input type="text" name="father" class="right-align" required />
  <br/><br/>
  E-MAIL:<input type="email" name="email" class="right-align" required />
  <br/><br/>
  CONTACT:<input type="phone" name="contact" class="right-align" minlength="7" maxlength="10" required />
  <br/><br/>
  COUNTRY:  
  <select name="country" class="select_country" required >
    <option value="">--Select--</option>
    <option value="ind">INDIA</option>   
    <option value="eng">ENGLAND</option>
    <option value="chi">CHINA</option>
    <option value="aus">AUSTRALIA</option>
  </select>
  <br/><br/>
  <input type="submit" value="SUBMIT" name="submit" />
</form>

JavaScript:

var form = document.getElementById('bhawesh')

function isEmpty(str) {
  return (!str || 0 === str.length || '' === str.trim())
}

function isInvalidEmail(str) {
  return (str.indexOf('@') < 1 || 
          str.lastIndexOf('.') + 2 >= str.length || 
          str.indexOf('@') + 2 > str.lastIndexOf('.'))
}

function submitFormHandler(evt) {
  var failures = 0
  // get the form form fields
  var formFields = evt.target.elements

  // disable default form action
  evt.preventDefault()

  // validate 'name' field
  if (isEmpty(formFields['name'].value)) {
    failures += 1
    alert('Enter the name')
    // focus on the form field
    formFields['name'].focus()
  }

  // validate 'father' field
  if (0 == failures && isEmpty(formFields['father'].value)) {
    failures += 1
    alert('Enter the Father\'s name')
    // focus on the form field
    formFields['father'].focus()
  }

  // validate 'email' field
  if (0 == failures && (isEmpty(formFields['email'].value) || 
      isInvalidEmail(formFields['email'].value))) {
    failures += 1
    alert('Enter the email')
    // focus on the form field
    formFields['email'].focus()
  }

  // validate 'contact' field
  if (0 == failures && isEmpty(formFields['contact'].value)) {
    failures += 1
    alert('Enter the contact')
    // focus on the form field
    formFields['contact'].focus()
  }

  // validate 'country' field
  if (0 == failures && isEmpty(formFields['country'].value)) {
    failures += 1
    alert('Select the country')
    // focus on the form field
    formFields['country'].focus()
  }

  if (0 === failures) {
    // get the form data
    var formData = new FormData(evt.target)
    // prepare AJAX request
    var request = new XMLHttpRequest()
    // get the method and action from the form
    var method = evt.target.method || 'POST'
    var action = evt.target.action || '#'

    // perform the AJAX request
    request.open(method, action)
    request.send(formData)
  }
}

if (form) {
  // attach form handler to submit event
  form.addEventListener('submit', submitFormHandler)
}

交换按钮的提交输入,然后使用验证功能为按钮添加事件处理程序并提交。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM