简体   繁体   English

突出显示无效的表单输入

[英]Highlighting invalid form inputs

I have been working on creating a form with a set of fields like username, passwords etc.... I want to make validation when the SUBMIT button is clicked. 我一直在努力创建一个包含用户名,密码等字段的表单....我想在单击SUBMIT按钮时进行验证。

I'm trying to get alert from my border color. 我正试图从边框颜色中获得警觉。 All fields are valid my border must change into Green color If it has any errors it should change to red color. 所有字段都有效我的边框必须更改为绿色如果有任何错误,它应该更改为红色。

Any one has any ideas regarding to my problem 任何人对我的问题都有任何想法

If anyone has any suggestion?? 如果有人有任何建议?

You can use jquery plugin.... here you are. 您可以使用jquery插件....在这里。 JQuery Form validation custom example JQuery表单验证自定义示例

Use jQuery validation plugin: http://docs.jquery.com/Plugins/Validation 使用jQuery验证插件: http//docs.jquery.com/Plugins/Validation

In this plugin, you have to define validation rules for the field. 在此插件中,您必须为该字段定义验证规则。 You can also set the error messages for given field for given validation rule. 您还可以为给定的验证规则设置给定字段的错误消息。

This plugin adds classes to valid and invalid field. 此插件将类添加到有效和无效字段。

You have to give the css for that class. 你必须给那个班级的CSS。

For example: 例如:

$(document).ready(function(){
        $(".my_form").validate({
                    rules:{  // validation rules
                            email_address: {
                                required:true,
                                email: true
                            },
                            password:{
                                minlength: 6
                            },
                            confirm_password: {
                                         equalTo:"#password"
                            }
                    },
                    messages: {
                        email_address: {
                           required: "Please enter email address",
                           email: "Please enter valid email address",
                       },
                       /*
                          likewise you can define messages for different field 
                          for different rule.
                       */
                    }
                    errorClass: "signup_error",  
                     /*This is error class that will be applied to 
                      invalid element. Use this class to style border. 
                      You can give any class name.*/
                });
      });

Once you click on submit button, and field is invalid, the plugin adds class to the element that you have specified as errorClass , and when you enter valid value in the field, the plugin will remove this class and will add 'valid' class by default. 单击提交按钮后,字段无效,插件会将类添加到您指定为errorClass的元素,当您在字段中输入有效值时,插件将删除此类并添加'valid'类默认。

You can use these two classes to style valid and invalid element using simple element. 您可以使用这两个类使用简单元素设置有效和无效元素的样式。

.valid {
   border-color:"green"
}

.signup_error {
  border-color:"red"
}

Hope this resolves your problem. 希望这可以解决您的问题。

Js i the way to go. 我顺便走了。 You can find some really good validators for jQuery should you google for it. 如果你谷歌的话,你可以找到一些非常好的jQuery验证器。

To custom build a simple validator I would go like this 要自定义构建一个简单的验证器,我会这样做

<form class="validator">
  <input type="text" name="my-input-1" data-validator="integer"/>
  <input type="text" name="my-input-2" data-validator="email"/>
  ....
</form>

<script>
   $("form.validator").submit(evt, function() {
      var errors = 0;
      $(this).find('[data-validator]').each(function(e, i) {
         var value = $(this).value;
         switch($(this).data('validator')) {
            case 'integer':
               if (!(parseFloat(value) == parseInt(value)) && !isNaN(value)) {
                  $(this).css({'border-color': '#FF0000'});
                  errors++;
               } else
                  $(this).css({'border-color': '#000000'});
               break;
            case 'email':
               if (..... // regex validate email ...) {
                  $(this).css({'border-color': '#FF0000'});
                  errors++;
               } else
                  $(this).css({'border-color': '#000000'});
               break;
         }
      });
      if (errors > 0) {
         // If you want to prevent default event execution no matter what
         evt.preventDefault();
         // If you want you other attached events to NOT run
         evt.stopPropagation();
         // signal failure
         return false;
      }

      // All is well, go on
      return true;
   });
</script>

of course it's always good practice to build functions for every validator and even better to wrap the whole thing in a jQuery widget (I would suggest using jQuery Widget Factory) which would allow you to enhance it in the future and keep you flexible to changes 当然,为每个验证器构建函数总是好的做法,甚至更好地将整个事物包装在jQuery小部件中(我建议使用jQuery Widget Factory),这将允许您在将来增强它并使您灵活地进行更改

Use this link 使用此链接

Use this for further usage beyond textbox highlighting 除了文本框突出显示之外,还可以使用它进一步使

You can use DOJO library to validate form fields. 您可以使用DOJO库来验证表单字段。 It's easy to implement. 它很容易实现。

Given below is the tutorial to implement dojo 下面给出了实现dojo的教程

http://dojotoolkit.org/documentation/tutorials/1.6/validation/ http://dojotoolkit.org/documentation/tutorials/1.6/validation/

and this is the working example you can see... 这是你可以看到的工作实例......

http://dojotoolkit.org/documentation/tutorials/1.6/validation/demo/dijitcheck.html http://dojotoolkit.org/documentation/tutorials/1.6/validation/demo/dijitcheck.html

I made a validation library just for general javascript purposes. 我为一般的javascript目的做了一个验证库。 It is even unit tested! 它甚至经过了单元测试! You can override whatever you want fairly easily as well: https://github.com/parris/iz 您也可以轻松覆盖任何您想要的内容: https//github.com/parris/iz

As far as highlighting invalid fields you can just change the style of that field or add a class. 至于突出显示无效字段,您只需更改该字段的样式或添加类即可。 The example below just changes the background color of the input and adds a message. 以下示例仅更改输入的背景颜色并添加消息。

Working example: http://jsfiddle.net/soparrissays/4BrNu/1/ 工作示例: http//jsfiddle.net/soparrissays/4BrNu/1/

$(function() {
    var message = $("#message"),
        field = $("#field");
    $("#the-form").submit(function(event) {
        if (iz(field.val()).alphaNumeric().not().email().valid){
            message.text("Yay! AlphaNumeric and not an email address");
            field.attr("style","background:green;");
        } else {
            message.text("OH no :(, it must be alphanumeric and not an email address");
            field.attr("style","background:red;");
        }
        return false;
    });
});​

The validator is called iz. 验证器称为iz。 It simply lets you chain validations together and it will tell you if everything passed or if you check the "errors" object it'll give you more specifics. 它只是让你将验证链接在一起,它会告诉你是否一切都通过了,或者如果你检查“错误”对象,它会给你更多细节。 Beyond that you can specify your own error messages. 除此之外,您可以指定自己的错误消息。 Check the docs on github. 检查github上的文档。

What is happening here is we are setting a click handler for the submit event once the page is ready. 这里发生的是我们正在为页面准备好后为提交事件设置一个点击处理程序。 return false; at the bottom of the submit callback prevents the form from submitting. 在提交回调的底部阻止表单提交。 If you return true; 如果你return true; the form will continue on. 表格将继续。 Instead of return false you could also event.preventDefault(); 而不是返回false,你也可以使用event.preventDefault(); but I prefer the return syntax for consistency. 但我更喜欢返回语法的一致性。 In the real world with multiple form elements you may do something like this (psuedo code): 在具有多个表单元素的现实世界中,您可以执行以下操作(伪代码):

var passed = true;
if (check field 1 is false)
    ...
if (check field 2 is false)
    ...
if (check field n is false)
    passed = false
    style and add message

if passed
    return true
else
    return false

The if statement checks the validation rules and makes changes to the DOM accordingly. if语句检查验证规则并相应地更改DOM。 By doing it in this way you are able to give a complete list of all passed and failed fields with a full description of what is incorrect. 通过这种方式,您可以提供所有已通过和失败字段的完整列表,并提供错误的完整描述。

我过去使用过这个插件 ,使实现非常简单,并且有很好的文档和示例。

My advice use jQuery 我的建议使用jQuery

to try first create multiple inputs and give them a class 尝试首先创建多个输入并为它们提供一个类

html: HTML:

<input type="text" class="validate" value="asdf" />
<input type="text" class="validate" value="1234" />
<input type="text" class="validate" value="asd123" />
<input type="text" class="validate" value="£#$&" />
<input type="text" class="validate" value="  " />

then use the code below to see how it works 然后使用下面的代码来看看它是如何工作的

jQuery: jQuery的:

// Validate Function
function validate(element) {
    var obj = $(element);
    if (obj.val().trim() != "") {
        // Not empty
        if (!/^[a-zA-Z0-9_ ]{1,10}$/.test(obj.val())) {
            // Invalid
            obj.css('border-color', '#FAC3C3');
            if (!obj.next().hasClass('error'))
            { obj.after('<span class="error">Please use letters or numbers only and not more than 10 characters!</span>'); }
            else
            { obj.next().text('Please use letters or numbers only and not more than 10 characters!'); }
        } else {
            // Valid
            obj.css('border-color', 'lightgreen');
            if (obj.next().hasClass('error'))
            { obj.next().remove(); }
        }
    } else {
        // Empty
        obj.css('border-color', '#FAC3C3');
        if (obj.next().hasClass('error'))
        { obj.next().text('This field cannot be empty!'); }
        else
        { obj.after('<span class="error error-keyup-1">This field cannot be empty!</span>'); }
    }
}

$(document).ready(function() {
    // Each
    $('.validate').each(function() {
        // Validate
        validate(this);
        // Key up
        $(this).keyup(function() {
            // Validate
            validate(this);
        });
    });
});

jsfiddle : http://jsfiddle.net/BerkerYuceer/nh2Ja/ jsfiddle: http//jsfiddle.net/BerkerYuceer/nh2Ja/

A server side validation example of your need. 您需要的服务器端验证示例。 You may try it out. 你可以尝试一下。

<?php

error_reporting(0);

$green = "border: 3px solid green";
$red="border: 3px solid red";
$nothing="";

$color = array ("text1"=>$nothing , "text2"=>$nothing) ;


if ( $_POST['submit'] ) {

    if($_POST['text1']) {
        $color['text1'] = $green;       
    }

    else $color['text1'] = $red;

    if($_POST['text2'] ) {
        $color['text2'] = $green;
    }

    else $color['text2'] = $red;
}



?>


<form method="post">
    <input type="text" name="text1" style="<?php echo $color ['text1']?>" value="<?php echo $_POST['text1']?>">
    <input type="text" name="text2" style="<?php echo $color ['text2']?>" value="<?php echo $_POST['text2']?>">
    <input type="submit" name="submit">


</form>

Note 注意

  1. Always sanitize user input. 始终清理用户输入。
  2. error_reporting off is not a good practice at all. error_reporting off根本不是一个好习惯。 I did it as this is not a code of production environment. 我这样做了,因为这不是生产环境的代码。
  3. Check before trying to access in the post array using isset or something similar function like this. 在尝试使用isset或类似函数访问post数组之前检查。
  4. Always check if a variable exist before using. 在使用之前,请务必检查变量是否存在。
$("#btn").click(function(){
        // Check all of them 
        if( $.trim($("#file").val()) == ""){
            $("#file").css("border","1px solid #ff5555");
        }else{
            $("#file").css("border","1px solid #cccccc");
            if( $.trim($("#showboxResimBaslik").val()) == ""){
                $("#showboxResimBaslik").css("border","1px solid #ff5555");
            }else{
                $("#showboxResimBaslik").css("border","1px solid #cccccc");
                if( $.trim($("#showboxResimEtiket").val()) == ""){
                    $("#showboxResimEtiket").css("border","1px solid #ff5555");
                }else{  
                    if($.trim($("#showboxResimSehir").val()) == ""){
                        $("#showboxResimSehir").css("border","1px solid #ff5555");
                    }else{
                        $("#showboxResimSehir").css("border","1px solid #cccccc");
                        $("#resimYukleForm").removeAttr("onSubmit");
                        $('#resimYukleForm').bind('submit', form_submit);
                    }
                }

            }

        }
    });

probably the easiest way is to use this javascript: http://livevalidation.com/examples#exampleComposite 可能最简单的方法是使用这个javascript: http//livevalidation.com/examples#exampleComposite

I think it suits your description the best. 我认为它最适合你的描述。

check below link, here i have only checked for empty fields and if the fields are empty then changed input fields id which will change input field border color. 检查下面的链接,这里我只检查空字段,如果字段为空,则更改输入字段ID,这将更改输入字段边框颜色。 http://jsfiddle.net/techprasad/jBG7L/2/ http://jsfiddle.net/techprasad/jBG7L/2/

I have used 我用过

$("#myb").click(function(){

that is on button click event but you can use submit event. 这是按钮单击事件,但您可以使用提交事件。

Here is what I would say is short precise and concise way to do this in jQuery. 这就是我要说的是在jQuery中执行此操作的简短精确和简洁的方法。

HTML: HTML:

<form id="myform" name="form"  action="http://www.google.com">
                    <div class="line"><label>Your Username</label><input class="req" type="text" /></div>
                    <div class="line"><label>Your Password</label><input class="req" type="password" /></div>
                    <div class="line"><label>Your Website</label><input class="req" type="text" /></div>
                    <div class="line"><label>Your Message</label><textarea  class="req"></textarea></div>
                    <div class="line"><input type="submit" id="sub"></submit>

                </form>

CSS: CSS:

.line{padding-top:10px;}
        .inline input{padding-left: 20px;}
        label{float:left;width:120px;}

jQuery: jQuery的:

$(function() {
            function validateform() {
                var valid = true;
                $(".req").css("border","1px solid green");
                $(".req").each(function() {
                    if($(this).val() == "" ||  $(this).val().replace(/\s/g, '').length == 0) {
                        $(this).css("border","1px solid red");
                        valid = false;
                    }
                });
                return valid;
                }

                $("#sub").click(function() {
                $('#myform').submit(validateform);
                    $('#myform').submit();
                });

        });

LIVE DEMO 现场演示

Well hi, you can use html5 "required" and "pattern" in your form's fields. 嗨,您可以在表单的字段中使用html5“required”和“pattern”。 You'll get red border if it's wrong and green if it's right. 如果它是错误的你会得到红色边框,如果它是正确的你会得到绿色。 You can even style the :valid and :invalid entry fields if the colors aren't which you wanted. 如果颜色不是您想要的颜色,您甚至可以设置:valid和:invalid输入字段。 I've never tested it but why not, it's better than nothing ;) 我从未测试过,但为什么不测试,它总比没有好;)

html5 solution html5解决方案

Firs Learn javascript, if you have some basic knowledge of js and need to know the logic, go on read.. First you need an event handler to run a function on form submit Easiest way is (though there are better ways) Firs学习javascript,如果你有一些js的基本知识并且需要知道逻辑,继续阅读..首先你需要一个事件处理程序来运行表单上的函数提交最简单的方法是(虽然有更好的方法)

<form action="som.php" onsubmit="functionName()">

form here 在这里形成

</form>

This will trigger the function called functionname. 这将触发名为functionname的函数。 In function name function access the input fields and validate using regular expressions 在函数名称函数中,访问输入字段并使用正则表达式进行验证

function functionName()
{
//verification code
if(verified)
{
//code to change border to green
}


}

You need to get the input fields and validate them. 您需要获取输入字段并验证它们。 If you don't know how to do that, get a few Javascript books If you need to validate as soon as value is typed use the on onchange event on input fields 如果您不知道如何操作,请获取一些Javascript书籍如果您需要在输入值时立即验证,请在输入字段上使用on onchange事件

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

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