EzDevInfo.com

jQuery-Form-Validator

jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code. jQuery Form Validator

In Java Script validation Using keyup for validating is not working in mozilla

In jquery form validation the keyup is not working mozilla but working fine in chrome.

here is the Javascript code

function validate() {  
    var msg;  
    if(document.myForm.userPass.value.length>5)
        msg="good";  
    else
        msg="poor";  
    document.getElementById("mylocation").innerText=msg;  
}  

here is the html code

<form name="myForm"> 
<input type="password" value="" name="userPass" onkeyup="validate()">   
Strength:<span id="mylocation">no strength</span>  
</form>  

Source: (StackOverflow)

How to send error message from servlet to jsp page?

My jsp page consists of a form that takes in an email address. I then use java to check if my postgresql database already contains that email address. Right now my servlet just redirects the user back to the Registration page if the email address already exists.

What I am trying to do is write an error message on the form "The email address you entered already exists" with java. I haven't figured out how to do it.

Is there some way I could do this with jQuery form validation? I am using that right now for required fields.


Source: (StackOverflow)

Advertisements

how to activate next div only when current div is valid using jquery?

This is my form. I have divided it into 3 divs

    <div id="signup-form">
      <div id="row">
        <form id="signForm">
           <div id="first-form">        
                    <fieldset id="body">
                        <fieldset>
                            <label for="name">Name</label>
                            <input type="text" name="user_name" id="user_name" />
                        </fieldset>
                        <fieldset>
                            <label for="mobile">Mobile</label>
                            <input type="text" name="mobile" id="mobile" />
                        </fieldset>
                         <a class="next" id="next1" rel='nofollow' href="#"><span>Next</span></a> 
                    </fieldset>

    </div>
    <div id="second-form">
           <fieldset>
              <label for="email">Email</label>
                <input type="text" name="user_email" id="user_email" />
            </fieldset>
            <fieldset>
                 <label for="password">Password</label>
                 <input type="password" name="pass_word" id="pass_word" />
            </fieldset>
            <a class="next" id="next2" rel='nofollow' href="#"><span>Next</span></a> 
    </div>
    <div id="third-form">
                        <fieldset>
                            <label for="city">City</label>
                            <input type="text" name="user_city" id="user_city" />
                        </fieldset>
                        <fieldset>
                            <label for="college">College</label>
                            <input type="text" name="college" id="college" />
                        </fieldset>
                        <fieldset>
                            <label for="branch">Branch</label>
                            <input type="text" name="branch" id="branch" />
                        </fieldset>
                        <input type="submit" id="signup" value="Sign Up" />
                 </div>
            </form>
         </div>
    </div>

These are the validations for my code that I have written. I have used validation.min.js plugin for validating the form

    var validator = $("#signForm").validate({
  rules: {
    user_name: "required", 
    user_email: {          
      required: true,
      email: true
    },
    mobile: {
      required: true,
      digits:true,
      maxlength:10,
      minlength:10
    },
    pass_word: {
      required: true
    },
    user_city: {
      required: true
    },
    college: {
      required: true
    },
    branch: {
      required: true
    }
  },
  messages: {
    user_name: "Please enter name.",
    user_email: {         
      required: "please enter email",
      email: "please enter valid email"
    },
    mobile: {         
      required: "please enter mobile number",
      email: "please enter valid mobile number",
      maxlength: "mobile number contains 10 digits",
      minlength: "max 10 digits allowed"
    },
    pass_word: "Please enter password.",
    user_city: "Please enter user city.",
    college: "Please enter college.",
    branch: "Please enter branch."
  },
  submitHandler: function(form) {
        form.submit();
    }
});

I am trying to get the code where initially first only the div first-form must be active and the remaining two divs second-form and third-form must be inactive and when the next is clicked in div first-form it must check for the validation of all the input elements in first-form and if all the elements are valid then only the second div i.e, second-form must be active. The same with the second-form, until all the input elements in second-form are valid the third-form must be inactive and must be active only when all the input elements in second-form are valid.

When I am trying to search for solution I found http://jsfiddle.net/c2y6r/1/. But in this example the jquery UI tabs are used, instead I do not want to use tabs. How can I do this with divs instead of tabs?


Source: (StackOverflow)

Html5 form validation with required and disabled element

I realize that you should never disable an element and also require it, because how could the user make it valid if it's disabled?

However, I have a <select> of products that I want my users to choose from. When they select one of the products another <select> for the product's models is populated, enabled, and required only if the product has one or more models. Otherwise, the model select is disabled and emptied.

While I like to think that my code is perfect and I can make it so that the model dropdown is never disabled and required at the same time, I'm not perfect. So, would the form be able to be submitted with a <select> that is disabled and required?

Update

Taken from w3.org:

Constraint validation: If the element is required, and its value IDL attribute applies and is in the mode value, and the element is mutable, and the element's value is the empty string, then the element is suffering from being missing.

Looked up specific of what it means to be "mutable".

A form control can be designated as mutable.

Note: This determines (by means of definitions and requirements in this specification that rely on whether an element is so designated) whether or not the user can modify the value or checkedness of a form control, or whether or not a control can be automatically prefilled.

Selects don't have a value, so it is determined by it's options.

The select element does not have a value; the selectedness of its option elements is what is used instead.

So, I think this means that if a <select> element was disabled and required, the form could be considered valid?


Source: (StackOverflow)

form validation not working in visualforce which working in html

Form validation is not working but same code is running in html and form validation also works i have uploaded all static resources please suggest me what changes in code are required. 1. I have uploaded static resourced successfully. 2. All files path is correct. 3. Suggest me if any changes necessary for html tag to visualforce tag

        <apex:stylesheet value="{!URLFOR($Resource.validation, 'valid/bootstrap.min.css')}"/>
        <apex:stylesheet value="{!URLFOR($Resource.validation, 'valid/formValidation.min.css')}"/>
        <apex:includeScript value="{!URLFOR($Resource.validation,'valid/bootstrap.min.js')}"/>
        <apex:includeScript value="{!$Resource.bootstrapjs}"/>
        <apex:includeScript value="{!URLFOR($Resource.validation,'valid/bootstrap1.min.js')}"/>
        <apex:includeScript value="{!URLFOR($Resource.validation,'valid/formValidation.min.js')}"/>
        <apex:includeScript value="{!URLFOR($Resource.validation,'valid/jquery.min.js')}"/>



    </head>

    <body>
        <form id="basicBootstrapForm" class="form-horizontal">
            <div class="form-group">
                <label class="col-xs-3 control-label">Full name</label>
                <div class="col-xs-4">
                    <input type="text" class="form-control" name="firstName" placeholder="First name" />
                </div>
                                </div>



                                   </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-xs-3 control-label" id="captchaOperation"></label>
                <div class="col-xs-4">
                    <input type="text" class="form-control" name="captcha" />
                </div>
            </div>



            <div class="form-group">
                <div class="col-xs-9 col-xs-offset-3">
                    <button type="submit" class="btn btn-primary" name="signup" value="Sign up">Submit</button>
                </div>
            </div>
        </form>

        <script>
        $(document).ready(function() {
            // Generate a simple captcha
            function randomNumber(min, max) {
                return Math.floor(Math.random() * (max - min + 1) + min);
            }
            $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));

            $('#basicBootstrapForm').formValidation({
                framework: 'bootstrap',
                icon: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    firstName: {
                        row: '.col-xs-4',
                        validators: {
                            notEmpty: {
                                message: 'The first name is required'
                            }
                        }
                    },

                 }   

            });
        });
        </script>
    </body>
</html>


Source: (StackOverflow)

Edit existing jQuery function to add upload file

I have some working code but want to add upload image field but with no success. My current code is:

Form:

<form id="add_product_form" enctype="multipart/form-data">
    <input id="uploadFile" type="file" name="image" class="img" /><br />
    <input id="status" type="checkbox" checked /><br />
    <input id="product" type="text" /><br />
    <label for="button" id="response"></label>
    <input type="button" id="button" value="Добави" /><br />
</form>

jQuery:

<script type="text/javascript">
$('document').ready(function(){
    $('#button').click(function(){

        var image = $('input[type=file]').val().split('\\').pop();
        function chkb(bool){ if(bool) return 1; return 0; } var status=chkb($("#status").is(':checked'));
        if($('#product').val()==""){ alert("enter name"); return false; } else { var product = $('#product').val(); } 

        jQuery.post("products_add_process.php", { 
            image: image,
            status: status, 
            product: product
            }, 

        function(data, textStatus) {
            $('#response').html(data);
            if(data == 1){
                $('#response').html("OK");
                $('#response').css('color','green');
                document.getElementById("add_product_form").reset();
            } else {
                $('#response').html("Not OK");
                $('#response').css('color','red');
            }
        });
    });
});
</script>

products_add_process.php:

<?php
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$status = $_POST['status'];
$product = $_POST['product'];

if($image_name == '') {
    echo "<script>alert('Select image')</script>";
    exit();
    } else {
        $random_digit=rand(0000000000,9999999999);
        $image=$random_digit.$image_name;
        move_uploaded_file($image_tmp_name,"uploads/$image");

        $query=mysql_query("INSERT INTO products(product, image, status) VALUES ('$product', '$image', '$status')");

        if(mysql_affected_rows()>0){
            $response = 1;
            echo "1";
            } else {
            $response = 2;
            echo "2";
            }
        }
?>

I put alert 'Select image' and then understand that $image_name is empty and maybe somewhere have to put some code to say that I want to send DATA TYPE. I try to add to form enctype="multipart/form-data" but won't work.

Where and what have to add in existing code to make sending data, without making very big changes because this code have in a lot of files and will be difficult to edit big part of codes.

Maybe have to add that form and jQuery are in php file which is called in other mother file and structure is something like this:

products.php /call products_add.php/
   products_add.php /where is the form and jQuery/
       products_add_process.php /called from products_add.php to upload data/

p.s. Sorry if I don't explain my problem well but I'm from soon at stackoverflow and still learning how to post my questions :)


Source: (StackOverflow)

Button loading and control property not getting changed on form submit

So I have a form which I validate before submit using jquery-form-validator plugin! But the problem here is few lines written on success is not getting executed when it goes step by step. However, they work fine if executed in console or executed with debugger. Really a wiered behavior!! Any workaround to come over from this?

JS

$.validate({
    form:'#contact-form',
    onError: function () {
        toastr.error("Please correct the below errors!", "Error");
        return false;
    },
    onSuccess: function () {
        $("#btnContactUs").button('loading'); //Not getting called
        $('.form-contact form').find('input,textarea').attr('readonly', true).addClass('disabled'); //Not getting called
        var formdata = new FormData($('.form-contact form').get(0));
        $.ajax({
            url: $("#contact-form").attr('action'),
            type: 'POST',
            data: formdata,
            processData: false,
            contentType: false,
            success:function(data)
            {
                if(data.result)
                {
                    toastr.success(data.message, "Success");
                    $('.form-contact form').get(0).reset();//Check this
                }
                else
                {
                    toastr.error(data.message, "Error");
                }
            },
            error:function(data)
            {
                toastr.error(data.message, "Error");
            }
        });
        $("#btnContactUs").button('reset');
        $('.form-contact form').find('input,textarea').attr('readonly', false).removeClass('disabled');
        return false; // Will stop the submission of the form
    }
});

On validation success it calls the Controller method through ajax but without executing first 2 lines.

UPDATE: Button #btnContactUs is a bootstrap button which has .button functionality to show loading text.


Source: (StackOverflow)

formvalidator.net compare password not working

I am using formValidator from FormValidator.net and I have a situation where I need to validate password and compare password fields and according to plugin this is how we it can be done.

<p>
  Password (at least 8 characters)
  <input name="pass_confirmation" data-validation="length" data-validation-length="min8"/>

  Confirm password
  <input name="pass" data-validation="confirmation"/>
</p>

and since I am using their latest version of plugin I also tried what they have suggested how to do it latest version > 2.2.1 as below:

<p>
      Password (at least 8 characters)
      <input name="pass_confirmation" data-validation="length" data-validation-length="min8"/>

      Confirm password
      <input name="pass" data-validation="confirmation" data-validation-confirm="pass_confirmation"/>
</p>

But still it is not comparing the password at all. Although I can say that minimum value comparision for password is happening properly. Have anyone worked on this plugin.? Is there any other way to do this?

$.validate({
  form: "#frmSample",
  validateOnBlur: true, // enable validation when input looses focus
  scrollToTopOnError: true, // Set this property to true if you have a long form
  borderColorOnError: "rgb(167, 3, 0)",
  borderColorOnSuccess: "#a94442",
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.43/jquery.form-validator.min.js"></script>
<form id="frmSample">
 <p>
  Password (at least 8 characters)
  <input name="pass_confirmation" data-validation="length" data-validation-length="min8">
  <br/>
  Confirm password
  <input name="pass" data-validation="confirmation">
</p>
</form>


Source: (StackOverflow)

Stop submitting before validation is done?

Hey guys I have a problem with one plugin. I am using this jquery form valdiation to validate my form, but if I have an AJAX call to submit the data then the validation is ignored. I tried setting a global variable and making a control statement at the AJAX call to stop of submitting it but when I did that the validation worked but it can't submit the data.

Validation

var isValid = 0;
    $.validate({
        form : '#comment-form',
        onSuccess : function() {
          isValid = 1;
          return false; 
        },
        validateOnBlur : false,
        errorMessagePosition : 'top',
        scrollToTopOnError : false,
    });

AJAX Submit Data:

$(document).ready(function() {
  if (isValid == 1)
  {
  $("#submitComment").click(function (e) {
    e.preventDefault();
    var name = $("#nameTxt").val();
    var comment = $("#commentTxt").val(); //build a post data structure
    var article = $("#articleID").val();
    var isFill = $("#isFillTxt").val();

    jQuery.ajax({
      type: "POST", // Post / Get method
      url: "<?php echo site_url('articles/create_comment/'); ?>", //Where form data is sent on submission
      dataType:"text", // Data type, HTML, json etc.
      data: "body=" + comment + "&name=" + name + "&article_id=" + article + "&isFillCheck=" + isFill, //Form variables
      success:function(response){
        $("#responds").append(response);
        document.getElementById("commentTxt").value="";
        document.getElementById("nameTxt").value="";
      },
      error:function (xhr, ajaxOptions, thrownError){
        alert(thrownError);
      }
    });
  });
  }
});

Source: (StackOverflow)

jquery-form validation callbacks not working

I am using jQuery-FormValidator plugin to validate form on client side but whatever the suggestion they have given in the above link to add a callback functions are not firing whereas proper errors will be displayed while trying to submit. What else I need to add to below code to make those events work?

$.validate("#contact-form",{
    validateOnBlur: true, // disable validation when input looses focus
    errorMessagePosition: 'top',
    scrollToTopOnError: true, // Set this property to true if you have a long form
    onError: function () {
        alert('hi');
        $('html,body').animate({
            'scrollTop': '2994'
        });
        toastr.error("Validation errors", "Error");
    },
    onSuccess : function() {
        alert('The form is valid!');
        return false; // Will stop the submission of the form
    }
});

Rendered HTML

<form action="/Home/SendMessage" class="wow bounceInUp has-validation-callback animated" data-wow-delay="0.2s" data-wow-offset="10" id="contact-form" method="post" style="visibility: visible;-webkit-animation-delay: 0.2s; -moz-animation-delay: 0.2s; animation-delay: 0.2s;">    <div class="row marginbot-20">
        <div class="col-md-6 xs-marginbot-20 has-error">
            <input class="form-control input-lg error" data-val="true" data-val-required="The name field is required." data-validation="length" data-validation-length="min5" id="name" name="name" placeholder="Enter name*" type="text" value="" current-error="The input value is shorter than 5 characters" style="border-color: red;">
        <span class="help-block form-error">The input value is shorter than 5 characters</span></div>
        <div class="col-md-6 has-error">
            <input class="form-control input-lg error" data-placement="top" data-toggle="tooltip" data-val="true" data-val-required="The email field is required." data-validation="email" id="email" name="email" placeholder="Enter email*" title="" type="text" value="" data-original-title="Your email id will be kept private" current-error="You have not given a correct e-mail address" style="border-color: red;">
        <span class="help-block form-error">You have not given a correct e-mail address</span></div>
    </div>
    <div class="row">
        <div class="col-md-6 xs-marginbot-20">
            <div class="form-group has-error">
                <input class="form-control input-lg error" data-placement="top" data-toggle="tooltip" data-val="true" data-val-required="The contact field is required." data-validation="custom" data-validation-regexp="^[789]\d{9}$" id="contact" name="contact" placeholder="Enter contact*" title="" type="text" value="" data-original-title="We will reach you with this contact info" current-error="The input value is incorrect" style="border-color: red;">
            <span class="help-block form-error">The input value is incorrect</span></div>
            </div>
        <div class="col-md-6 has-error">
            <input class="form-control input-lg error" data-val="true" data-val-required="The subject field is required." data-validation="length" data-validation-length="10-100" id="subject" name="subject" placeholder="Enter subject*" type="text" value="" current-error="The input value must be between 10-100 characters" style="border-color: red;">
        <span class="help-block form-error">The input value must be between 10-100 characters</span></div>

        <div class="col-md-12">
            <div class="form-group has-error">
                <textarea class="form-control error" cols="25" data-val="true" data-val-required="The message field is required." data-validation="length" data-validation-length="30-400" id="message" name="message" placeholder="Your Message [Max 400 characters]*" rows="4" current-error="The input value must be between 30-400 characters" style="border-color: red;"></textarea>
                <div class="text-right"> <span id="maxlength">400</span> characters left</div>
            <span class="help-block form-error">The input value must be between 30-400 characters</span></div>
            <button type="submit" class="btn btn-skin btn-lg btn-block btn-border" id="btnContactUs">
                Send Message
            </button>
        </div>
    </div>
</form>

Source: (StackOverflow)

jQuery Validate compare elements

I would like to achieve the following: a user can enter 3 keywords in a form, but these keywords must be 3 different keywords. I would like to enforce this using the jQuery Validate plugin.

I have tried the following code:

jQuery.validator.addMethod('notEqualTo', function(value, element, params) {
    var result = true;
    for (var i = 0; i < params.length; i++) {
        var par = params[i];
        if (value === $(par).val()) {
            result = false;
        } 
    }
    return result;
}, 'Keywords must be different');

$('#uploadForm').validate({
    rules: {
        keyword1: {
            required: true
        },
        keyword2: {
            required: true,
            notEqualTo: [$('#keyword1'), $('#keyword3')]
        },
        keyword3: {
            required: true,
            notEqualTo: [$('#keyword2'), $('#keyword1')]
        }
    }
    ...
});

But when keyword2 and keyword3 are the same, it does not work properly. Also, when keyword3 is entered first and after that keyword1, it also does not work properly.

How can I get this to work?


Source: (StackOverflow)

jQuery validation in rails not working as expected

I have been working on this issue for a day and tried various solutions but none of them seem to be working.

<%= form_tag("/report", method: "post", id: 'report-form') do |f|%>

    <div class="form-group">
        <%= radio_button_tag :report_reason, 1 %>
        <%= label_tag :report_reason_l, 'Inappropriate Photo' %>
    </div>
    <div class="form-group">
        <%= radio_button_tag :report_reason, 2 %>
        <%= label_tag :report_reason_l, 'Seems Like Spam' %>
    </div>
    <div class="form-group">
        <%= radio_button_tag :report_reason, 3 %>
        <%= label_tag :report_reason_l, 'Underage User' %>
    </div>
    <div class="form-group">
        <%= radio_button_tag :report_reason, 0 %>
        <%= label_tag :report_reason_l, 'Other' %>
    </div>
    <div class="form-group">
        <%= text_area_tag 'report_description', nil, placeholder: 'Description...', :autofocus => true, rows: 3, class: 'form-control' %>
    </div>
    <div class="form-group">
        <%= submit_tag "Report", class: "btn btn-primary", id:'submit-report' %>
    </div>

<% end %>
<script>
$(function() {
    $('#report-form').validate({
        rules: {
            'report_description' : {
                required : true
            }
        },
        messages: {
            'report_description' : {
                required : "Please mention the reason for reporting this"
            }
        }
        submitHandler: function(form) {
            form.submit();
        }
    });
});
</script>

Here the validation is: if the user can't leave the description blank.

jsfiddle link is here.
Where am I going wrong with the validation??


Source: (StackOverflow)

Error message breaks layout when displayed

I have the following field on my page

enter image description here

Which is constructed with the following HTML

<div style="margin-bottom: 10px" class="input-group">
  <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
   @Html.TextBoxFor(m => m.Username, new { @class = "form-control", placeholder = "Choose a username (max 25)", Maxlength = "25", autocomplete = "off" })
</div>

pretty basic stuff, I currently have jquery form validation embedded into my application which looks like this:

I have removed all the fields besides this one.

 $('#registrationForm').validate({
    rules: {
        "Username": "required",

    },
    messages: {
        "Username": "Please enter your chosen Username",

    }
});

When I leave the field blank and press submit it looks like this

enter image description here

As you can see the user glyphicon height has been increased to cater for the error message.

The rendered HTML looks like this:

<div class="input-group" style="margin-bottom: 10px">
 <span class="input-group-addon">
  <i class="glyphicon glyphicon-user"></i>
 </span>
<input id="Username" class="form-control" type="text" value="" placeholder="Choose a username (max 25)" name="Username" data-val-required="The Username field is required." data-val="true" autocomplete="off" maxlength="25">
</div>

Can anyone suggest why this might be happening?

Update

This is what is render when the error message is displayed

<div class="input-group" style="margin-bottom: 10px">
 <span class="input-group-addon">
  <i class="glyphicon glyphicon-user"></i>
 </span>
<input id="Username" class="form-control error" type="text" value="" placeholder="Choose a username (max 25)" name="Username" data-val-required="The Username field is required." data-val="true" autocomplete="off" maxlength="25">
<label class="error" for="Username">Please enter your chosen Username</label>
</div>

enter image description here

** Update after adding additional styles to .Error class **

enter image description here


Source: (StackOverflow)

validator is undefined in asp.net mvc

I have a bootstrap modal containing two radio button: the first one contain a form and the second contain a kendo grid. I have to chose to create a new object from the form or to select an existant object from the grid To be able to select an existant object from the grid I disabled the validation from the form like this:

<div >
                    @Html.LabelFor(model => model.xxxxx)
                    <div >
                        @{ Html.EnableClientValidation(false); }
                        @Html.EditorFor(model => model.xxxx, new { htmlAttributes = new { @class = "form-control" } })
                        @{ Html.EnableClientValidation(true); }
                    </div>
                </div>

And then to make my validation work when creating a new object from the form I used a fuction to tests if form proprities are empty or not like this:

if (xxx== '') {
            alert("  le champ xxx est obligatoire");
            return false;
        }

Every thing is doing right and I get my object correctly but when I open my firefox console I have an error message like this :

TypeError: validator is undefined settings = validator.settings;

I didn’t know what is the cause of this error !!
Please help me.


Source: (StackOverflow)

formvalidation.io form validation. If "other", please explain

I'm using the FormValidation plugin in Bootstrap and am loving it, except I can't figure out one thing. I have a form with an "other" check box. If you check "other", I want an explanation typed into another field. I've been all over the website (formvalidation.io), but I'm not finding an answer. Unfortunately, I know just enough JS to be dangerous.

Here's the code for the validator I'm using on the check boxes.

'work_type[]': {
    validators: {
    choice: {
        min: 1,
        message: 'Please choose at least one work type.'
    }
    }
}

There's another field called "other_work" that I would like to require a string in if work_type has a value of "Other Work".


Source: (StackOverflow)