JavaScript验证表单错误消息

时间:2016-11-25 17:54:57

标签: javascript html regex

我一直在进行此表单验证,当我将其显示为警报时,我收到错误消息,但我似乎无法使用document.getElementById("").innerHTML =进行打印。

我也有这个表格

     <form id="form" name="form" method="post" onSubmit="return validate(this) && reportErrors(errors)" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  

      var ck_name = /^(Mr|Mrs)\. (.+)? (.+)?/i;
      var ck_street = /^[0-9]{2,3} +[a-z A-Z]+ +(Street|Road)$/;
      var ck_postalInput = /^([D-JL-Wd-jl-w]{2})([1-9]{1})[\-\s]?([D-JL-Wd-         jl-w]{1})([1-9]{2})$/;
      var ck_phoneInput =  /^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*         ([\d]{3})[\.\-\s]?([\d]{4})$/;
      var ck_emailInput =/^[a-zA-Z]+(.)+[a-zA-Z]+(@mohawkcollege)+(.com|.ca|.org)$/;

     function validate(form){
     var nameInput = form.nameInput.value;
     var streetInput = form.streetInput.value;
     var postalInput = form.postalInput.value;
     var phoneInput = form.phoneInput.value;
     var emailInput = form.emailInput.value;

     var errors = [];

     if (!ck_name.test(nameInput)) {
     errors[errors.length] = "Full name not entered correctly.";
     }

     if (!ck_street.test(streetInput)) {
     errors[errors.length] = "Street name not entered correctly.";
     }
     if (!ck_postalInput.test(postalInput)) {
     errors[errors.length] = "Postal not entered correctly.";
     }

     if (!ck_phoneInput.test(phoneInput)) {
      errors[errors.length] = "Phone number not entered correctly.";
     }

     if (!ck_emailInput.test(emailInput)){
     errors[errors.length] = "email not entered correctly.";
     }


     if (errors.length > 0) {
     reportErrors(errors);
     return false;
      }

     return true;
     }

     function reportErrors(errors){
     var msg = "Please Enter Valide Data...\n";
     for (var i = 0; i<errors.length; i++) {
     msg += "\n" + ". " + errors[i];
     }
     document.getElementById("error").innerHtml=msg;
     }

1 个答案:

答案 0 :(得分:0)

我刚修好了:

var ck_street = "/^[0-9]{2,3} +[a-z A-Z]+ +(Street|Road)$/";
var ck_postalInput = "/^([D-JL-Wd-jl-w]{2})([1-9]{1})[\\-\\s]?([D-JL-Wd- jl-w]{1})([1-9]{2})$/";
var ck_phoneInput = "/^[+]?([\\d]{0,3})?[\\(\\.\\-\\s]?([\\d]{3})[\\)\\.\\-\\s]* ([\\d]{3})[\\.\\-\\s]?([\\d]{4})$/";
var ck_emailInput ="/^[a-zA-Z]+(.)+[a-zA-Z]+(@mohawkcollege)+(.com|.ca|.org)$/";