简体   繁体   中英

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.

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 Form validation custom example

Use jQuery validation plugin: 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.

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.

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.

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

Use this link

Use this for further usage beyond textbox highlighting

You can use DOJO library to validate form fields. It's easy to implement.

Given below is the tutorial to implement dojo

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

I made a validation library just for general javascript purposes. It is even unit tested! You can override whatever you want fairly easily as well: 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/

$(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. 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.

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; the form will continue on. Instead of return false you could also 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. 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

to try first create multiple inputs and give them a class

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:

// 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/

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. 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.
  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

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. 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.

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:

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

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. 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. I've never tested it but why not, it's better than nothing ;)

html5 solution

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)

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

form here

</form>

This will trigger the function called 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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