如何使用php中的javascript验证在相应的输入字段下打印错误消息

时间:2016-10-15 10:25:29

标签: javascript php validation

如果在相应的输入字段下打印错误消息如果留空并且填写时必须删除错误消息,如何继续进行我还没有使用javascript进行验证。

脚本代码

function validateForm() {
    var a = document.forms["student_reg"]["name"].value;
    if (a == null || a == "") {
        alert("Name must be filled out");
        return false;
    }
     var b = document.forms["student_reg"]["email"].value;
     if (b == null || b == "") {
        alert("Email must be filled out");
        return false;
    }
     var c = document.forms["student_reg"]["username"].value;
     if (c == null || c == "") {
        alert("Username must be filled out");
        return false;
    }
     var d = document.forms["student_reg"]["password"].value;
     if (d == null || d == "") {
        alert("Password must be filled out");
        return false;
    }
     var e = document.forms["student_reg"]["roll_no"].value;
     if (e == null || e == "") {
        alert("Roll no must be filled out");
        return false;
    }
}

html代码在这里

<body>

 <a href="login.php">Login</a>
        <form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
                <p>NAME:</p>
                <input type="text" name="name" value="" >
                <span class="error"><p id="name_error"></p></span

                <p>EMAIL:</p>
                <input type="text" name="email" value="" >
                <span class="error"><p id="email_error"></p></span

                <p>USERNAME:</p>
                <input type="text" name="username" value="" >
                <span class="error"><p id="username_error"></p></span

                <p>PASSWORD:</p>
                <input type="password" name="password" value="" >
                <span class="error"><p id="password_error"></p></span

                <p>ROLL NO:</p>
                <input type="number" name="roll_no" value="" >
                <span class="error"><p id="roll_no_error"></p></span
                <br/>
                <br/>
                <br/>

                <input type="submit" name="submit" value="submit">

 </form>
 </body>

4 个答案:

答案 0 :(得分:3)

您可以尝试以下代码:

它将检查错误并在显示所有错误消息后最后返回。

function validateForm() {
    var error = 0;
    var a = document.forms["student_reg"]["name"].value;
    document.getElementById('name_error').innerHTML = '';
    if (a == null || a == "") {
        // alert("Name must be filled out");
        error++;
        document.getElementById('name_error').innerHTML = 'Name must be filled out';
    }

    var b = document.forms["student_reg"]["email"].value;
    document.getElementById('email_error').innerHTML = '';
    if (b == null || b == "") {
        // alert("Email must be filled out");
        error++;
        document.getElementById('email_error').innerHTML = 'Email must be filled out';
    }

    var c = document.forms["student_reg"]["username"].value;
    document.getElementById('username_error').innerHTML = '';
    if (c == null || c == "") {
        // alert("Username must be filled out");
        error++;
        document.getElementById('username_error').innerHTML = 'Username must be filled out';
    }

    var d = document.forms["student_reg"]["password"].value;
    document.getElementById('password_error').innerHTML = '';
    if (d == null || d == "") {
        // alert("Password must be filled out");
        error++;
        document.getElementById('password_error').innerHTML = 'Password must be filled out';
    }

    var e = document.forms["student_reg"]["roll_no"].value;
    document.getElementById('roll_no_error').innerHTML = '';
    if (e == null || e == "") {
        // alert("Roll no must be filled out");
        error++;
        document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
    }

    if(error>0) {
        return false;
    }
    return true;
}

答案 1 :(得分:1)

将所有name属性保留在array中,并在loop中进行验证。由于您的IDname属性相关,请将name_error连接起来,以获取ID占位符的error

&#13;
&#13;
function validateForm() {
  var names = ['name', 'email', 'username', 'password', 'roll_no'];
  var errorCount = 0;
  names.forEach(function(el) {
    var val = document.forms["student_reg"][el].value;
    if (val == null || val == "") {
      document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
      ++errorCount;
    }
  });
  if (errorCount) return false;
}
&#13;
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
  <p>NAME:</p>
  <input type="text" name="name" value="">
  <span class="error"><p id="name_error"></p></span>

  <p>EMAIL:</p>
  <input type="text" name="email" value="">
  <span class="error"><p id="email_error"></p></span>

  <p>USERNAME:</p>
  <input type="text" name="username" value="">
  <span class="error"><p id="username_error"></p></span>

  <p>PASSWORD:</p>
  <input type="password" name="password" value="">
  <span class="error"><p id="password_error"></p></span>

  <p>ROLL NO:</p>
  <input type="number" name="roll_no" value="">
  <span class="error"><p id="roll_no_error"></p></span>
  <br/>
  <br/>
  <br/>

  <input type="submit" name="submit" value="submit">

</form>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

简单表单它保留Span for the Error msgspan Id在这里非常重要。您需要使用css为错误制作颜色

 <form id="loginform" name="loginform" action="" method="post">
     <label>Name</label>
        <input type="text" name="username" />
          <p></p>
          <span id="usernameError"></span>
          <p></p>
     <label>Pwd</label>
        <input type="password" name="password" />
           <p></p>
           <span id="passwordError"></span>
           <p></p>
        <input type="submit" value="Submit" />
    </form>

<强>脚本

<script type="application/javascript">
window.onload = function(){
    function handleinput(){
        if(document.loginform.username.value == ""){
            document.getElementById("usernameError").innerHTML = "You must enter a username";
            return false;
        }

        if(document.loginform.password.value == ""){
            document.getElementById("passwordError").innerHTML = "You must enter a password";
            return false;
        }
    }

    document.getElementById("loginform").onsubmit = handleinput;
}
</script>

答案 3 :(得分:0)

如果没有设置任何值,您可以遍历表单student_reg的所有元素以验证电子邮件和必填项并在相应的输入字段下打印错误消息:

function validateForm() {
  var form = document.forms['student_reg'],
      inputs = form.getElementsByTagName('input'),
      errors = form.getElementsByClassName('error'),
      regex = /\S+@\S+\.\S+/,
      setErrorMsg = function(str, msg) {
        return str.replace('_', ' ') + ' ' + msg;
      },
      countErrors = 0;

  // loop all elements but not submit button
  for (var i = 0, l = inputs.length - 1; i < l; i++) {
    var val = form[inputs[i].name].value;
    
    // clear all errors
    errors[i].innerHTML = '';

    // validate email
    if (inputs[i].name === 'email' && !regex.test(val)) {
      errors[i].textContent = setErrorMsg(inputs[i].name, 'should be valid');
      countErrors++;
    }

    // validate required
    if (!val) {
      errors[i].textContent = setErrorMsg(inputs[i].name, 'field is required');
      countErrors++;
    }
  }

  return countErrors === 0;
}
.error {
  padding-top: 8px;
  color: red;
  display:block }
.error:first-letter {
  text-transform: uppercase}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
  <p>NAME:</p>
  <input type="text" name="name" value="">
  <span class="error"></span>

  <p>EMAIL:</p>
  <input type="text" name="email" value="">
  <span class="error"></span>

  <p>USERNAME:</p>
  <input type="text" name="username" value="">
  <span class="error"></span>

  <p>PASSWORD:</p>
  <input type="password" name="password" value="">
  <span class="error"></span>

  <p>ROLL NO:</p>
  <input type="number" name="roll_no" value="">
  <span class="error"></span>
  <br/>
  <br/>

  <input type="submit" name="submit" value="submit">
</form>