Reputation: 890
I am trying to create a custom validator method for phone numbers. I would like to allow the user to enter the phone # in any format, ie. (800)555-1212, 800.555.1212, etc. then simply strip out the non-numeric characters, reformat the text in my own format and copy into the input field. I have played with different methods, but can't seem to find the right combination. My latest attempt goes something like:
jQuery.validator.addMethod("validphone", function(value, element, param) {
mNum = value.replace(/[^0-9]/g, '');
if(mNum.length != 10)
return false;
else
return this.optional(element) || (mNum.length == 10);
}, jQuery.validator.messages.number);
This seems to validate as desired, but I can't find the proper way to put the reformatted number back into the input field. Logically I think it should be $(this).val(mNum);
but this doesn't seem to work. Perhaps it fails due to being called from the validation method?
Any thoughts will be greatly appreciated!
Upvotes: 0
Views: 732
Reputation: 490657
It looks like you would set the val()
on element
instead, in your arguments signature.
Upvotes: 2