简体   繁体   English

简单的表单验证。 面向对象

[英]Simple form validation. Object-oriented

Problem statement: It is necessary for me to write a code, whether which before form sending will check all necessary fields are filled.问题陈述:我需要写一个代码,在发送表单之前是否会检查所有必填字段是否已填写。 If not all fields are filled, it is necessary to allocate with their red colour and not to send the form.如果未填写所有字段,则需要以红色分配而不是发送表格。

Now the code exists in such kind:现在代码以这种方式存在:

function formsubmit(formName, reqFieldArr){     
    var curForm = new formObj(formName, reqFieldArr);
    if(curForm.valid)
        curForm.send();
    else
        curForm.paint();    
}


function formObj(formName, reqFieldArr){
    var filledCount = 0;
    var fieldArr = new Array();
    for(i=reqFieldArr.length-1; i>=0; i--){
        fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
        if(fieldArr[i].filled == true)
        filledCount++;
    }
    
    if(filledCount == fieldArr.length)
        this.valid = true;
    else
        this.valid = false;
    
    
    this.paint = function(){
        for(i=fieldArr.length-1; i>=0; i--){
            if(fieldArr[i].filled == false)
                fieldArr[i].paintInRed();
            else
                fieldArr[i].unPaintInRed();
        }
    }
    
    this.send = function(){
        document.forms[formName].submit();
    }
}


function fieldObj(formName, fName){
    var curField = document.forms[formName].elements[fName];
    
    if(curField.value != '')
        this.filled = true;
    else
        this.filled = false;
        
    this.paintInRed = function(){
        curField.addClassName('red');
    }
    
    this.unPaintInRed = function(){
        curField.removeClassName('red');
    }
}

Function is caused in such a way:函数是这样引起的:

<input type="button" onClick="formsubmit('orderform', ['name', 'post', 'payer', 'recipient', 'good'])"  value="send" />

Now the code works.现在代码可以工作了。 But I would like to add " dynamism " in it.但我想在其中添加“活力”。

That it is necessary for me: to keep an initial code essentially, to add listening form fields (only necessary for filling).这对我来说是必要的:本质上保留初始代码,添加监听表单字段(仅用于填写)。

For example, when the field is allocated by red colour and the user starts it to fill, it should become white.例如,当字段被分配为红色并且用户开始填充时,它应该变为白色。

As a matter of fact I need to add listening of events: onChange, blur for the blank fields of the form.事实上,我需要添加事件监听:onChange,表单空白字段的模糊。 As it to make within the limits of an initial code.由于它在初始代码的范围内进行。

If all my code - full nonsense, let me know about it.如果我所有的代码都是废话,请告诉我。 As to me it to change using object-oriented the approach.至于我改用面向对象的方法。


Give me pure Javascript solution, please.请给我Javascript 解决方案。 Jquery - great lib, but it does not approach for me. Jquery - 很棒的库,但它适合我。

To keep your HTML clean, I suggest a slightly different strategy.为了保持 HTML 干净,我建议采用稍微不同的策略。

  1. Use a framework like jQuery which makes a lot of things much more simple.使用像 jQuery 这样的框架可以让很多事情变得更简单。

  2. Move all the code into an external script.将所有代码移动到外部脚本中。

  3. Use the body.onLoad event to look up all forms and install the checking code.使用 body.onLoad 事件查找所有表单并安装检查代码。

  4. Instead of hardcoding the field values, add a css class to each field that is required:不是对字段值进行硬编码,而是向每个需要的字段添加一个 css 类:

     <input type="text" ... class="textField required" ...>

    Note that you can have more than a single class.请注意,您可以拥有多个类。

When the form is submitted, examine all fields and check that all with the class required are non-empty.提交表单后,检查所有字段并检查所有required的类是否为非空。 If they are empty, add the class error otherwise remove this class.如果它们为空,则添加类error否则删除此类。 Also consider to add a tooltip which says "Field is required" or, even better, add this text next to the field so the user can see with a single glance what is wrong.还可以考虑添加一个工具提示,上面写着“需要字段”,或者更好的是,在字段旁边添加此文本,以便用户一眼就能看出哪里出了问题。

In the CSS stylesheet, you can then define a rule how to display errors.在 CSS 样式表中,您可以定义如何显示错误的规则。

For the rest of the functionaly, check the jQuery docs about form events .对于其余的功能,请查看有关表单事件jQuery 文档

Has made.造成。

function formsubmit(formName, reqFieldArr){     
    var curForm = new formObj(formName, reqFieldArr);
    if(curForm.valid)
        curForm.send();
    else{
        curForm.paint();    
        curForm.listen();
    }
}


function formObj(formName, reqFieldArr){
    var filledCount = 0;
    var fieldArr = new Array();
    for(i=reqFieldArr.length-1; i>=0; i--){
        fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
        if(fieldArr[i].filled == true)
        filledCount++;
    }

    if(filledCount == fieldArr.length)
        this.valid = true;
    else
        this.valid = false;


    this.paint = function(){
        for(i=fieldArr.length-1; i>=0; i--){
            if(fieldArr[i].filled == false)
                fieldArr[i].paintInRed();
            else
                fieldArr[i].unPaintInRed();
        }
    }

    this.send = function(){
        document.forms[formName].submit();
    }

    this.listen = function(){
        for(i=fieldArr.length-1; i>=0; i--){
            fieldArr[i].fieldListen();
        }
    }
}

function fieldObj(formName, fName){
    var curField = document.forms[formName].elements[fName];

    this.filled = getValueBool();

    this.paintInRed = function(){
        curField.addClassName('red');
    }

    this.unPaintInRed = function(){
        curField.removeClassName('red');
    }

    this.fieldListen = function(){
        curField.onkeyup = function(){
            if(curField.value != ''){ 
                curField.removeClassName('red');
            }
            else{
                curField.addClassName('red');
            }
        }
    }

    function getValueBool(){
        if(curField.value != '')
            return true;
        else
            return false;
    }
}

This code is not pleasant to me, but it works also I could not improve it without rewriting completely.这段代码对我来说并不愉快,但它也有效,如果不完全重写,我无法改进它。

jQuery adds a lot of benefit for a low overhead. jQuery 为低开销增加了很多好处。 It has a validation plugin which is very popular.它有一个非常受欢迎的验证插件。 There are some alternatives as well but I have found jQuery to be the best.还有一些替代方案,但我发现 jQuery 是最好的。

Benefits好处

  • small download size小下载大小
  • built in cross browser support内置跨浏览器支持
  • vibrant plug-in community充满活力的插件社区
  • improved productivity提高生产力
  • improved user experience改善用户体验

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

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