0

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 :)

Janey
  • 1,260
  • 3
  • 17
  • 39

2 Answers2

1

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.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Thanks for the reply, I've just come back to validation so I'll give this a go :) – Janey Mar 24 '14 at 17:39
  • I've found an issue with this... if I enter incorrect data and update it shows the error... if I then close the popup and re-open it it opens with the error message still there, rather than blank. Do you have any ideas about what would cause this? Please see code below for an example. Thakns – Janey Mar 25 '14 at 17:08
  • @Janey, popup? jQuery Validate doesn't have anything to do with popups. – Sparky Mar 25 '14 at 18:03
  • @Janey, I see. You must use the plugin's `success` handler to manually clear out your popup. [This question](http://stackoverflow.com/questions/14741688/how-to-display-messages-from-jquery-validate-plugin-inside-of-tooltipster-toolti) uses a similar concept to yours. You'll need to study it and adapt it to your special situation... i.e. - it's different for Tooltipster than qTip2, etc... just depends on your popup plugin. But it's a whole new/different issue and you would need to post it as a new question. – Sparky Mar 25 '14 at 18:10
0

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
Janey
  • 1,260
  • 3
  • 17
  • 39