简体   繁体   English

JS表单验证(正则表达式或其他)

[英]JS Form validation (Regex, or anything)

I have a script here that is supposed to run when triggered. 我这里有一个脚本,应该在触发时运行。 However, it will only work if the variable passwd is not used in my if else statements. 但是,只有在if else语句中未使用变量passwd时,它才有效。 NEWLY UPDATED JS: 最新更新的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 的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>

(Sorry for the mess!) (对不起,一团糟!)

EDIT: The script works but the the password is not working as it should be. 编辑:该脚本可以工作,但密码不能正常工作。 Please see the comments 请看评论

Quick glance shows at least 2 problems with that area: 快速浏览一下该区域至少有两个问题:

  • passwd could be null and pass through the outer if condition. passwd可以为null并通过外部if条件。 Attempting length on it would cause an error 尝试length会导致错误

    You may want to wrap the inner conditionals in an else block 您可能需要将内部条件包装在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); 
  • In JS, it's passwd.length not length() 在JS中,它是passwd.length而不是length()

You should use the JS console to verify what errors are appearing. 您应该使用JS控制台来验证出现了哪些错误。

I see the problem, .length is a property, not a method. 我看到了问题, .length是属性,而不是方法。 Your length check should be: 您的长度检查应为:

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

One more note, foo == null || foo == "" 还有一个注释, foo == null || foo == "" foo == null || foo == "" can be simplified to !foo as null and "" are both falsy values in JS. foo == null || foo == ""可以简化为!foo因为null""都是JS中的虚假值。

Im not expert but i recommend you evaluate mail field with regex ( /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/ ) and i created a separated function for validate each of the values in the form for add a text error, then another validation who evaluate if all the fiels pass the evaluation, like yours but i made it liek that: if(validateName(nameVar) && validateEmail(emailVar) this is all the code that i made, that validate a correct form mail, a name with alphabetical form and phone without null value: 我不是专家,但我建议您使用正则表达式( /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/ ),并且我创建了一个单独的函数来验证表单中的每个值以添加文本错误,然后另一个验证人评估所有字段是否都通过了评估,就像您的那样,但是我让它看起来很: 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
    }
};

and this is the html code: 这是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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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