javascript - 基本的 javascript 表单验证 - 使用相同的函数验证相同的输入类型

标签 javascript jquery forms function validation

我一直使用 jQuery validate() 来处理表单,但最近在升级到我们的 XMPie 软件后遇到了问题(我们进行有针对性的通信)。

新版本的 XMPie 需要 jQuery 1.10.2,该版本不受 validate() 支持,因此我手动进行验证。

我可以通过为每个输入编写单独的函数来轻松进行验证,但这意味着至少要重写部分代码以针对特定的输入名称或 ID。

我想知道的是为什么我不能为特定输入类型(例如简单的文本字段)编写通用函数并让输入在 focusout() 上调用该函数,并将其自身作为参数传递?

如果我有两个文本输入,“fullName”和“userName”,为什么我不能使用

$(document).ready(function () {
    var inputName = "";
    var inputValue = "";
    var inputAlert = "";
    $("input").focusout(function () {
        inputIdentify(this);
        console.log(inputName);
        inputGetValue(this);
        console.log(inputValue);
        if (this.type == "text") {
            console.log("YES");
            textValidate(inputName, inputValue);
        }
    });

    function inputIdentify(theInput) {
        inputName = theInput["name"];
        console.log(inputName);
        return inputName;
    }

    function inputGetValue(theInput) {
        inputValue = theInput["value"];
        return inputValue;
    }

    function textValidate(theInput, inputValue) {
        console.log(theInput,inputValue);
        var letters = /^[A-Za-z ]+$/;
        if (inputValue.match(letters)) {
            $(theInput).addClass("correct");
            return true;
        } else {
            $(theInput).removeClass("correct");
            $(theInput).addClass("incorrect");

            // alert('Username must have alphabet characters only');
            $(inputName).focus();
            return false;
        }
    }
});

删除并添加简单的 css 类(彩色边框)来指示问题字段?

感谢和问候,

马尔科姆

最佳答案

您没有将正确的参数传递给 textValidate()。您将 inputName 作为 theInput 传递,但 textValidate() 使用 $(theInput) 访问输入元素。您应该将 this 作为该参数传递:

textValidate(this, inputValue);

此外,您对全局变量的使用是糟糕的设计。由于 inputIdentify()inputGetValue() 返回值,因此您应该将返回值分配给局部变量,而不是让这些函数设置全局变量。

   $("input").focusout(function () {
        var inputName = inputIdentify(this);
        console.log(inputName);
        var inputValue = inputGetValue(this);
        console.log(inputValue);
        if (this.type == "text") {
            console.log("YES");
            textValidate(this, inputValue);
        }
    });

    function inputIdentify(theInput) {
        var inputName = theInput["name"];
        console.log(inputName);
        return inputName;
    }

    function inputGetValue(theInput) {
        var inputValue = theInput["value"];
        return inputValue;
    }

关于javascript - 基本的 javascript 表单验证 - 使用相同的函数验证相同的输入类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553306/

相关文章:

javascript - 调整图像大小并附加到 HTML 表单的正确方法?

javascript - 如何临时设置所有元素的 tabindex 属性并能够将所有元素重置为其原始 tabindex?

javascript - URI 错误 : malformed URI sequence?

jquery - 如何使用jquery切换显示/隐藏帖子回复?

javascript - ASP.NET MVC3 表单集合在 jQuery ajax post 期间为 0

javascript - 动态添加表单元素后应用javascript

javascript - 动态添加输入元素以形成并将值存储在数据库中

javascript - 透明图像背景html5 Canvas

javascript - rails 。 jQuery 表单提交字段模糊

javascript - 添加动画以向下滚动到 jquery 中的特定 div