July 13, 2012

How to use remote method of jquery validation?

Question by Sachin

This is my validation code

$('#reg_form').validate({
            onkeyup: false,
            errorClass: 'error',
            validClass: 'valid',
            rules: {
                username: {
                    required: true,
                    minlength: 5,
                    //remote: "checkusername.php"
                },
                password: {
                    required: true,
                    minlength: 5,
                },
                confirm_password: {
                    required: true,
                    minlength: 5,
                    //equalTo: "#password",
                },
                secretQuestion: "required",
                secretAnswer: "required",
                emailId: {
                    required: true, 
                    email: true,
                    remote: "checkemail.php"
                },
                termsConditions: "required",                
            },
            messages:{
                username: {
                    required: "Please enter Username",
                    minlength: "Please enter atleast 5 characters",

                },
                password: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                },
                confirm_password: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long",
                    //equalTo: "Please enter the same password as above" 

                },
                secretQuestion: "Please select your question",
                secretAnswer: "Please enter your secret answer",
                emailId: {
                    required: "Please enter a valid email address",
                    remote: "Email is aleardy is exists! please try with onother",
                    },
                termsConditions: "Please accept our Terms and COnditions"
            },
            highlight: function(element) {
                $(element).closest('div').addClass("f_error");
            },
            unhighlight: function(element) {
                $(element).closest('div').removeClass("f_error");
            },
            errorPlacement: function(error, element) {
                $(element).closest('div').append(error);
            }
        });

Answer by Starx

There is very easy explanation of the remote method on the jQuery plugin page.

As per my suggestions to you! to understand the method better, use the method in expanded form.

emailId: {
    required: true, 
    email: true,
    remote: {
        url: "checkmail.php", //the url of the page you are querying
        type: "post", //the method you are going to use to send the data
        data: { //the data you are going to send
           email: function() { 
             return $("#email").val(); //send the value of email
           }
        }
    }
},

But, your code should work the way it is.

May 29, 2012

jQuery Validate – Success event?

Question by Probocop

I am using the jQuery Validate plugin on my site, and then submitting the form via ajax. Is there an event I can use when the entire form is valid?

Answer by Starx

There is no event for this. Just check the status using a simple if statement.

if($("form").valid()) {
 //go ahead
}

But, if you are trying to have a workaround solution to catch the valid event, you can do something like this

$("form").submit(fucntion() {
    if($(this).valid()) {
       //go ahead
    } else {
       //do some error handling
    }
});
April 18, 2012

jQuery validation – How to not accept a file extension

Question by Maxime Lepers

I would like to find a way to refuse a specific extension in a text field at form submission.

I have a field where you can specify a URL but this URL shouldn’t link to a PDF file.

I figured that there is a jQuery validation methods called accept that does exactly the contrary of what I want to do.

Is there a way to use with a not() function or something similar? It would be way easier than creating a custom validation method.

Answer by Starx

Here is any idea

var ext = $('#fieldid').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','jpg', ...]) == -1) {
    alert('invalid extension!');
}
April 12, 2012

Jquery custom validation non numeric

Question by Brian Perin

I’m trying to write a custom validation function for jquery. The rule should be that the field cannot ONLY be numeric. I know how to write only numeric or only alpha but I want the rule to say that a value of “12345” would fail, but “12345A” would be validated

This is what I have for non numeric

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !value.match(/[0-9]+/);
},"Only alphabatic characters allowed.");

but I can’t figure out how to do not ONLY numeric.


Working script

Here are three rules that might be helpful, the last one is the one that answers this question.

 jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value.indexOf(" ") < 0 && value != ""; 
}, "No spaces please");

jQuery.validator.addMethod("alpha", function(value, element) {

    return this.optional(element) || /^[a-z]+$/i.test(value);
},"Letters only please.");

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || isNaN(Number(value));
},"String cannot be numeric");

Answer by Elliot Bonneville

Use parseInt (which returns NaN if the operand isn’t strictly a number) like this:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(parseInt(value));
},"Only alphabatic characters allowed.");

Don’t use != in this case or you could wind up with this unpleasant situation.


According to Ken Browning‘s comment, parseInt might not be appropriate here. Try this instead:

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !isNaN(Number(value));
},"Only alphabatic characters allowed.");

Answer by Starx

I think this regex should be enough

/[a-z]/i.test(value);

Usage

jQuery.validator.addMethod("nonNumeric", function(value, element) {
    return this.optional(element) || !(/[a-zA-Z]/i.test(value));
},"Only alphabatic characters allowed.");
February 27, 2012

jQuery validation not working when radio button selected

Question by Jacob1

I have jQuery validation for my form. There is a radio box (attendance) and 2 drop down menus (colour and shade).

It works perfectly if the user logs in for the very first time. However because I have retreived the value from the database based on what they have selected before, if the user has already selected their choice and log back in, if they previously selected ‘No’ then my jQuery does not work. The two dropdown menus submit and are not greyed out as they should be. But if I click on ‘No’ radio box it does. Not sure if issue lies with jQuery or my radio button.

If the user logged in for the first time and selects ‘No’, they boxes grey out immediately.

jQuery validation:

<script src="jquery.js"></script>
 <script>      
    $( function(){    
            function validate(id){       
                var enabled = ($("input[name='attendance" + id + "']:checked").val() == 'Yes');         
                if(enabled){              
                    //Please select option is selected              
                    if($("#colour" + id)[0].selectedIndex == 0){                 
                    alert('Please make your colourselection');                  
                    return false;             
                    }              
                    //Please select option is selected              
                    if($("#shade" + id)[0].selectedIndex == 0){                  
                        alert('Please select your shade');                  
                        return false;             
                    }   
                }     
                return true;    
            };

            $("input[name^='attendance']").click(function() {  

                var id = this.name.replace('attendance', '');      
                $("#colour" + id + ", #shade" + id).prop("disabled", this.value == 'No');         
                validate(id);    
            });      
           $("input:submit").click(function(){         
               var retVal = true;
               $.each([1], function(i, val){
                  retVal = (validate(val) && retVal);
               });
                return retVal;   
           }); 
         }); 
  </script>

radio button:

<input name="attendance1" type="radio" id="Yes" value="Yes" checked="CHECKED" <?php if($row3['attendance1']=="Yes") { echo "checked"; }?>/>Attend with pleasure 
<br />
<input name="attendance1" type="radio" id="No" value="No" <?php if($row3['attendance1']=="No") { echo "checked"; }?>/>Decline with regret 

Answer by Starx

The problem I see is this part

checked="CHECKED" <?php if($row3['attendance1']=="Yes") { echo "checked"; }?>

This will render to the following if $row3['attendance1'] is “Yes”

checked="CHECKED" checked

So this will create problem. Remove checked="CHEKCED" part.

July 20, 2010

How to mark required field in jQuery Validate

Question by Henning

I’m using jQuery Validate and xVal to validate in input forms. This works great.
However, I do want to mark my required fields with an asterix (*) or something like that to show which field is actually required.

I could do this by hand, but since I already generate my validation rules with xVal I thought I could mark the required fields automatically based on the provided rules.

Is there a way to hook into either xVal or jQuery Validate to retrieve the rules, or somehow make them mark my required fields?

I’m using the latest versions of jQuery and jQuery Validate.

Thanks

Answer by Starx

Give the class required to the form elements, and use the following code

$(document).ready(function() {
     $('<span style="color:red;">*</span>').insertAfter('.required');
});

This will attach “*” to every elements with required class

Hope it helps

June 2, 2010

How to conditionally execute a jquery validation?

Question by Chendur Pandian

I am validating form using jquery validation plugin……

 rules: {
    Name: "required",
    MobileNo: {
           required: true,
           minlength: 10, remote: '<%=Url.Action("getClientMobNo", "Clients") %>'
               },
    Address: "required"
            },
    messages: {
        Name: "please provide a client name",
        MobileNo: {
        required: "Please provide a mobile phone no",
        rangelength: jQuery.format("Enter at least {0} characters"),
        remote: jQuery.format("This MobileNo is already in use")
      },
      Address: "please provide client address"
   },

This works pretty well on add form validation but i use the same form for edit here they can use the same mobile no,but my plugin validates that mobileno saying there is already a mobileno… But how to execute remote attribute based on a condition,

   MobileNo: {
           required: true,
           minlength: 10,
          if($("#HfId").val() == ""){ 
            remote: '<%=Url.Action("getClientMobNo", "Clients") %>'
             }
          },

Is this a valid jquery conditional validation statement…. How to skip remote attribute based on a condition….

Answer by Starx

Well, I would do something like this

for example my php page is member.php

to add, send a URL like this member.php?action=add

<? 
$action = $_GET['action'];
?>
<script>
        $("#frmmember").validate({
      rules: { 
        name: { 
                <? if($action=='add') { ?>
                      required: true, 
               <? } ?>
                      rangelength: [4, 50] },
        email: { required: true, rangelength: [5, 50], email: true },
        phone: { required: true, number:true, rangelength: [7, 10] }
        },
      onkeyup: false
    });
</script>

In this case, the validation rule required=true is only going to apply if there is “add” in the url variable "action"

How to get TinyMCE and Jquery validate to work together?

Question by chobo2

I am using jquery validate and the jquery version of tinymce.

I found this piece of code that makes tinymce to validate itself every time something changes in it.

Hi

I am using the jquery validate with my jquery tinymce so I have this in my code

    // update validation status on change
    onchange_callback: function (editor)
    {
        tinyMCE.triggerSave();
        $("#" + editor.id).valid();
    },

This works however there is one problem. If a user copies something from word it brings all that junk styling with it what is usually over 50,000 characters. This is way over my amount of characters a user is allowed to type in.

So my jquery validation method goes off telling me that they went over the limit. In the mean time though tinymce has cleaned up that mess and it could be possible now the user has not gone over the limit.

Yet the message is still there.

So is there a better function call I can put this in? Maybe tell tinymce to delay the valid when a paste is happening, or maybe a different callback?

Anyone got any ideas?

Answer by Starx

Oh yeah, I also faced this problem.

So, I fixed it by calling the validation on the click event of a button instead.

$("#buttontosave").click(function() {
         tinyMCE.triggerSave();
         var status;
         status = $("#myform").valid(); //Validate again
         if(status==true) { 
             //Carry on
         }
         else { }
});

This works try it.

For additional resources try

http://blog.rebeccamurphey.com/2009/01/12/jquery-validation-and-tinymce/

http://tinymce.moxiecode.com/punbb/viewtopic.php?id=21588

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_23941005.html

...

Please fill the form - I will response as fast as I can!