提交前进行表格数据验证

时间:2018-05-16 12:48:42

标签: javascript

在此表单中,我希望当我提交表单时,它将验证表单然后提交,但此处表单未经验证即提交。每当我点击提交按钮时,它会要求验证,但没有验证它会被提交到数据库。我想onsubmit,它要求验证,当插入有效数据时,表单将提交。

<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>

2 个答案:

答案 0 :(得分:0)

删除onsubmit属性并附上提交事件处理程序以在提交之前处理表单。

HTML表单:

<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)
}

答案 1 :(得分:0)

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