JS表单验证(正则表达式,或任何东西)

时间:2016-07-08 16:07:29

标签: javascript regex

我这里有一个脚本,应该在触发时运行。但是,只有在我的if else语句中没有使用变量passwd时,它才有效。 新推出的JS:

function validateForm() {
    var name = document.forms["myForm"]["name"].value;
    var phone = document.forms["myForm"]["phone"].value;
    var email = document.forms["myForm"]["email"].value;
    var add = document.forms["myForm"]["address"].value;
    var passwd = document.forms["myForm"]["password"].value;
    var matchesCount = email.split("@").length - 1;
    var matchesCount2 = email.split(".").length - 1;
    var error = "";
    if (!name || !phone || !email || !add || !passwd) {
        error+="All must be filled out \n"

        if(phone.search(/^[0-9]*$/) == -1  || phone.length != 8){
            error+="- Phone number can only contain digits \n";}

        if(passwd.search(/^[0-9a-zA-Z]*$/) == -1){
            error+="- Password needs to be alphanumeric \n";
        }

        if(passwd.length <8 || passwd.length > 16){
            error+="- Password contain only 8-16 digits \n";
        }

        if(matchesCount > 1 || matchesCount2 < 1){
            error+="- Please enter a valid email \n";
        }
        alert(error);
        return false;
    }
}   

HTML

<div id="newaccount">
        <table id="tablenewuser">
                <form name="myForm" action="ControllerServlet" onsubmit="return validateForm()" method="post">
                    <tr>
                        <td class="newusertd">Name:<span class="price">*</span></td>
                        <td class="newusertd"><input style="color: black;" type="text" name="name" class="Btn"></td>
                    </tr>
                    <tr>
                        <td class="newusertd">Contact Number:<span class="price">*</span></td>
                        <td class="newusertd"><input style="color: black;" type="text" name="phone" placeholder="98989898"class="Btn"></td>
                    </tr>
                    <tr>
                        <td class="newusertd">Email:<span class="price">*<br></span></td>
                        <td class="newusertd"><input style="color: black;" type="text" name="email" placeholder="xxx@hello.com" class="Btn"></td>
                    </tr>
                    <tr>
                        <td class="newusertd">Address:<span class="price">*</span></td>
                        <td class="newusertd"><input style="color: black;" type="text" name="address" class="Btn"></td>
                    </tr>
                    <tr>
                        <td class="newusertd">Password:<span class="price">*</span><br>(8-16 Characters with<br>one UPPERCASE & numbers)</td>
                        <td class="newusertd"><input style="color: black;" type="password" name="password" class="Btn">
                    </tr>
                    <tr>
                        <td class="newusertd"></td>
                        <td class="newusertd">
                            <input style="color: black;" type="submit" value="Create Account" class="Btn"/></td>
                    </tr>
                </form> 
        </table>
    </div>

(抱歉这个烂摊子!)

编辑:脚本有效,但密码不能正常工作。请参阅评论

3 个答案:

答案 0 :(得分:0)

快速浏览显示该区域至少有2个问题:

  • passwd可以是null并通过外部if条件。在其上尝试length会导致错误

    您可能希望将内部条件包装在else

    if (name == null || name == "" || phone == null || phone == "" || email == null || email == "" || add == null || add == ""
            || passwd == null || passwd == "") {
      error+="All must be filled out \n";
    } else {
      // other conditions
    }
    if (error) alert(error);
    
  • 在JS中,passwd.length不是length()

您应该使用JS控制台来验证出现的错误。

答案 1 :(得分:0)

我看到问题,.length是属性,而不是方法。您的长度检查应该是:

if (passwd.length >= 8 && passwd.length <= 16) {
     error += "- Only 8-16 digits \n";
}

还有一个注意事项,foo == null || foo == ""可以简化为!foonull""都是JS中的虚假值。

答案 2 :(得分:0)

我不是专家,但我建议您使用正则表达式(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)评估邮件字段,我创建了一个单独的函数,用于验证表单中的每个值以添加文本错误,然后另一个验证谁评估是否所有fiels通过了评估,就像你的一样,但我让它说谎:if(validateName(nameVar) && validateEmail(emailVar)这是我所做的所有代码,验证正确的表单邮件,字母表格的名称和没有空值的电话:

function validateName(nameVar) {
  var nameReg = /^[a-zA-Z'.\s]{1,40}$/;
  return nameReg.test(nameVar);
}
function validateEmail(emailVar) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test(emailVar);
}

function email() {
    var nameVar = $('#name').val();
    var emailVar = $('#email').val();
    var phoneVar = $('#phone').val();
    var messageVar = $('#message').val();
    if(!validateName(nameVar) ) {
        console.log("dentro");
        $('#nameError').text("Por favor ingresa un nombre valido");
    }else{
        $('#nameError').text("");

    }
    if(!validateEmail(emailVar) || emailVar == "") {
        $('#emailError').text("Por favor ingresa un correo valido");
    }else{
        $('#emailError').text("");
    }
    if(phoneVar == "") {
        $('#phoneError').text("Por favor ingresa un número telefonico");
    }else{
        $('#phoneError').text("");
    }
    if(validateName(nameVar) && validateEmail(emailVar) && emailVar != "" && phoneVar != ""){
            var data = {};
            data.name = nameVar;
            data.email = emailVar;
            data.phone = phoneVar;
            data.message = messageVar;
            //here your validate code with array of values ready for doing something
    }
};

这是html代码:

<h4 class="title-yellow contacto" id="title-yellow">Envianos un mensaje</h4>
                            <div class="row">&nbsp;</div>
                                    <div class="row">
                                        <div class="col-md-6 form-group">
                                            <input class="form-control" id="name" name="nombre" placeholder="Nombre" type="text" required >
                                        </div>

                                        <div class="col-md-6 form-group">
                                            <input class="form-control" id="email" name="email" placeholder="Email" type="email" required >
                                        </div>

                                    </div>
                                    <div class="row">
                                        <div class="col-md-12 form-group">
                                            <input class="form-control" id="phone" name="telefono" placeholder="Tel&eacute;fono" type="tel" required >
                                        </div>
                                    </div>
                                    <textarea class="form-control" id="message" name="mensaje" placeholder="Mensaje" rows="4">
                                    </textarea>
                                    <br>
                                    <div class="row">
                                        <div class="col-md-12 form-group">

                                            <button class="email nohover pull-right" id="mail" onclick="email()">ENVIAR</button>
                                            <p id="demo"></p>
                                            <div id="nameError"></div>
                                            <div id="emailError"></div>
                                            <div id="phoneError"></div>
                                            <div id="ajaxMessage"></div>       
                                        </div>




                                    </div>