Question

I'm creating a small jquery mobile project and have decided to use jqueryvalidation http://jqueryvalidation.org/ for form validation. I have a popup box where the user enters a number which is either their phone or email (unfortunately this has to stay like this because of the database) so I want to use the validation to say that the field must either contain email: or digits:.

Do you know if this is possible? Or a workround? Using depends: won't work either in this case as there is no conditional that will work on every database (the primary phone/email will not always be filled).

                      <form id='addNumber' action ='' method='post' data-ajax='false'>
                        <div class="ui-field-contain">
                        <label for="phoneType">Type</label>
                            <select name="phoneType" id="phoneType" data-native-menu="false">
                                <?php echo $phoneInnerOptions; ?>
                            </select>
                        </div>
                        <div class="ui-field-contain">
                            <label for="phoneNumber">Number</label>
                            <input type="text" name="phoneNumber" id="phoneNumber" value="">
                        </div> 
                        <div class="ui-field-contain">
                            <label for="primary">Primary Contact</label>
                            <select name="primary" id="primary" data-native-menu="false" >
                                <option value="1">Primary Phone</option>
                                <option value="2">Primary Email</option>
                                <option value="3"></option>
                            </select>
                        </div> 
                        <div class='ui-grid-a'>

                            <div class='ui-block-a'><input type='submit' value='Update' class='ui-btn ui-btn-inline' data-transition='pop' /></div>
                            <div class='ui-block-b'><a href='#' id="addNumberReset" class='ui-btn' data-rel='back' data-transition='pop'>Cancel</a></div>
                        </div>
                    </form>

And the current validation:

 $().ready(function() {     
                    // validate add number form
                 $("#addNumber").validate({
                        errorPlacement: function(error, element) {
                            error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
                        },
                        rules: {
                            phoneNumber: "required",
                        },
                        messages: {
                            phoneNumber: "Please enter a valid phone or email",
                        }
                    }); //end validate
                });// end function

Any help or advise with this one would be appreciated :)

Was it helpful?

Solution

Your best option in this case is to just write your own rule using the .addMethod() method.


simple example from docs:

jQuery.validator.addMethod("myrule", function(value, element) {
    // return 'true' to pass validation or return 'false' to fail validation
    return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
}, "Please specify the correct domain for your documents");

markup to declare this example rule:

rules: {
    myfield: {
        myrule: true  // only passes validation if "http://mycorporatedomain.com" is entered
    }
}

simple example from docs using parameters:

jQuery.validator.addMethod("myrule", function(value, element, params) {
    // return 'true' to pass validation or return 'false' to fail validation
    return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));

markup to declare this example rule:

rules: {
    myfield: {
        myrule: [5,20] // only passes validation if '25' is entered
    }
}

this.optional(element) in both examples makes the field entry "optional". If you also want the field required, just remove this part.

You can browse through the additional-methods.js file to see dozens of real working examples of this method.

OTHER TIPS

Heres the code I ended up using incase anyone else might need it.. thanks for the help on this one sparky

//creating the new rule
//Matches UK landline + mobile, accepting only 01-3 for landline or 07 for mobile to    exclude many premium numbers
jQuery.validator.addMethod('phonesUK', function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g,'');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[45789]\d{8}|624\d{6})))$/);
});

//use phonesUK or standard email
jQuery.validator.addMethod("phoneOrEmail", function(value, element) {
return this.optional(element) ||
($.validator.methods["phonesUK"].call(this, value, element)) ||
($.validator.methods["email"].call(this, value, element));
}, "Please enter a valid phone number or email address");

//apply it to my page
    $(document).on("pagecreate", function () {      
                    // validate new number form
                    $("#addNumber").validate({
                        errorPlacement: function(error, element) {
                            error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
                        },
                        rules: {

                            phoneNumber: 
                                {
                                    phoneOrEmail: true,
                                    required: true,
                                }

                        },
                        messages: {
                            phoneNumber: "Please enter a valid phone number or email address",
                        },

                        //check if valid - post if is
                        submitHandler: function(form) {
                            $('#PopUpAddNumber').popup('close');
                            $.post("customer_AddNewNumber.php", $("#addNumber").serialize(),  function(response)
                            {
                                 LoadCustomerNumber();
                            });

                        }
                    }); //end validate
                                        //reset form after validate
                    $('#addNumberReset').click(function () {
                    $('#addNumber').validate().resetForm();
                    });
                }); // end function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top