1

嗨,我真的坚持这一点,因为我是一个 javscript 初学者,这让我大吃一惊。

有没有人知道如何编写以下 javascript 表单验证?我确信这很简单,但我想不出这个来挽救我的生命。

感谢您分享您的知识。

我需要在没有 jquery 的情况下编写以下表单验证。每当遇到错误时,阻止提交表单。我需要使用 window.onload 函数来分配验证回调函数。有 4 个输入由 javascript 代码验证。javascript也需要在它自己的文件中。

验证规则如下:

输入:用户名;需要(是);验证(长度必须为 5-10 个字符)。输入:电子邮件;需要(是);验证(必须有 @ 符号,必须有句点)。输入:街道名称;必填(否);验证(必须以数字开头)。输入:出生年份;需要(是);验证(必须是数字)。

我的代码如下所示:


HTML:


<!DOCTYPE html>
<html>
<head>


<script defer="defer" type="text/javascript" src="form.js"></script>


</head>
<body>
<form action="fake.php">
    Username*: <input type="text" class="required" name="u"/><br/>
    Email*: <input type="text" class="required" name="p"/><br/>
    Street address: <input type="text" class="numeric" name="s"/><br/>
    Year of birth*: <input type="text" class="required numeric" name="b"/><br/>


    <input type="submit"/><br/>
</form>
</body>
</html>

JS

document.forms[0].elements[0].focus();

document.forms[0].onsubmit=function(){

for(var i = 0; i < document.forms[0].elements.length; i++){

var el = document.forms[0].elements[i];

if((el.className.indexOf("required") != -1) && 
  (el.value == "")){

alert("missing required field");
 el.focus();
el.style.backgroundColor="yellow";
 return false;
}

if((el.className.indexOf("numeric") != -1) && 
 (isNaN(el.value))){


alert(el.value + " is not a number");
 el.focus();
el.style.backgroundColor="pink";
 return false;              
  }
 }
}
4

3 回答 3

1

无需更改您的大部分代码...更新您的代码以进行其他验证,例如长度(需要一个类 verifylength 来验证长度)等等....

试试这个

HTML

<form action="fake.php">Username*:
<input type="text" class="required verifylength" name="u" />
<br/>Email*:
<input type="text" class="required email" name="p" />
<br/>Street address:
<input type="text" class="numeric" name="s" />
<br/>Year of birth*:
<input type="text" class="required numeric" name="b" />
<br/>
<input type="submit" />
<br/>
</form>

JAVASCRIPT

document.forms[0].elements[0].focus();
document.forms[0].onsubmit = function () {
for (var i = 0; i < document.forms[0].elements.length; i++) {
    var el = document.forms[0].elements[i];
    if ((el.className.indexOf("required") != -1) && (el.value == "")) {
        alert("missing required field");
        el.focus();
        el.style.backgroundColor = "yellow";
        return false;
    } else {
        if (el.className.indexOf("verifylength") != -1) {
            if (el.value.length < 5 || el.value.length > 10) {
                alert("'" + el.value + "' must be 5-10 charater long");
                el.focus();
                el.style.backgroundColor = "pink";
                return false;
            }
        }
    }

    if (el.className.indexOf("email") != -1) {
        var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
        var emailTest = regEx.test(el.value);
        if (!emailTest) {
            alert("email not valid");
            el.focus();
            el.style.backgroundColor = "yellow";
            return false;
        }
    };

    if ((el.className.indexOf("numeric") != -1) && (isNaN(el.value))) {
        alert(el.value + " is not a number");
        el.focus();
        el.style.backgroundColor = "pink";
        return false;
    }
 }
}

工作小提琴

于 2013-03-29T08:16:28.957 回答
0

类似于...的东西

//username 5-10 chars
var uVal = document.getElementsByTagName("u").value;
if (uVal.length < 5 || uVal.length > 10) return false;

//email needs @ and .
var eVal = document.getElementsByTagName("p").value;
if !(eVal.match('/.*@.*\./g')) return false;

//street starts w/ num
var sVal = document.getElementsByTagName("s").value;
if !(sVal.match('/^[0-9]/g')) return false;

我认为正则表达式已关闭+未经测试:)

于 2013-03-29T04:06:13.370 回答
0

这是您工作中的 javascript 验证对象。希望您可以根据需要进行一些修改。

风格

<style>
    .valid {border: #0C0 solid 1px;}
    .invalid {border: #F00 solid 1px;}
</style>

HTML 表单

<div>
    <form id="ourForm">
        <label>First Name</label><input type="text" name="firstname" id="firstname" class="" /><br />  
        <label>Last Name</label><input type="text" name="lastname" id="lastname" class="" /><br />  
        <label>Username</label><input type="text" name="username" id="username" class="" /><br />
        <label>Email</label><input type="text" name="email" id="email" class="" /><br />  
        <input type="submit" value="submit" class="" />  
    </form>
</div>

在结束标签之前调用脚本

<script src="form_validation_object.js"></script>

form_validation_object.js

/*
 to: dom object
 type: type of event
 fn: function to run when the event is called
 */
function addEvent(to, type, fn) {
    if (document.addEventListener) { // FF/Chrome etc and Latest version of IE9+
        to.addEventListener(type, fn, false);
    } else if (document.attachEvent) { //Old versions of IE. The attachEvent method has been deprecated and samples have been removed.
        to.attachEvent('on' + type, fn);
    } else { // IE5
        to['on' + type] = fn;
    }
}

// Your window load event call
addEvent(window, 'load', function() {
    /* form validation object */
    var Form = {
        validClass: 'valid',
        inValidClass: 'invalid',
        fname: {
            minLength: 1,
            maxLength: 8,
            fieldName: 'First Name'
        },
        lname: {
            minLength: 1,
            maxLength: 12,
            fieldName: 'Last Name'
        },
        username: {
            minLength: 5,
            maxLength: 10,
            fieldName: 'Username'
        },
        validateLength: function(formElm, type) {
            //console.log('string = ' + formElm.value);
            //console.log('string length = ' + formElm.value.length);
            //console.log('max length=' + type.maxLength);
            //console.log(Form.validClass);
            if (formElm.value.length > type.maxLength || formElm.value.length < type.minLength) {
                //console.log('invalid');
                //alert(formElm.className);
                if (formElm.className.indexOf(Form.inValidClass) == -1) {
                    if (formElm.className.indexOf(Form.validClass) != -1) {
                        formElm.className = formElm.className.replace(Form.validClass, Form.inValidClass);
                    } else {
                        formElm.className = Form.inValidClass;
                    }
                }

                //alert(formElm.className);
                return false;
            } else {
                //console.log('valid');
                //alert(formElm.className.indexOf(Form.validClass));
                if (formElm.className.indexOf("\\b" + Form.validClass + "\\b") == -1) { // regex boundary to match whole word only  http://www.regular-expressions.info/wordboundaries.html
                    //formElm.className += ' ' + Form.validClass;
                    //alert(formElm.className);
                    if (formElm.className.indexOf(Form.inValidClass) != -1)
                        formElm.className = formElm.className.replace(Form.inValidClass, Form.validClass);
                    else
                        formElm.className = Form.validClass;
                }
                return true;
            }
        },
        validateEmail: function(formElm) {
            var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
            var emailTest = regEx.test(formElm.value);
            if (emailTest) {
                if (formElm.className.indexOf(Form.validClass) == -1) {
                    formElm.className = Form.validClass;
                }
                return true;
            } else {
                formElm.className = Form.inValidClass;
                return false;
            }
        },
        getSubmit: function(formID) {
            var inputs = document.getElementById(formID).getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].type == 'submit') {
                    return inputs[i];
                }
            }
            return false;
        }
    }

    /* call validation object */
    var ourForm = document.getElementById('ourForm');
    var submit_button = Form.getSubmit('ourForm');
    submit_button.disabled = 'disabled';

    function checkForm() {
        var inputs = ourForm.getElementsByTagName('input');
        if (Form.validateLength(inputs[0], Form.fname)) {
            if (Form.validateLength(inputs[1], Form.lname)) {
                if (Form.validateLength(inputs[2], Form.username)) {
                    if (Form.validateEmail(inputs[3])) {
                        submit_button.disabled = false;
                        return true;
                    }
                }
            }
        }
        submit_button.disabled = 'disabled';
        return false;
    }

    checkForm();
    addEvent(ourForm, 'keyup', checkForm);
    addEvent(ourForm, 'submit', checkForm);

});

JSBin http://jsbin.com/ezujog/1的工作示例

于 2013-03-29T05:05:25.497 回答