简体   繁体   中英

jQuery Validate plugin not working for phone number

I have a form that needs to validate both US and UK phone numbers(preferably based on what the user selects from the dropdown menu next to the input. I have the following form code:

<form id="phone">
<div class="col-md-10">
    <div class="modal-header" style="text-align: center;">
         <h5>Get a link on your phone</h5> 
        <div class="input-group">
            <div class="input-group-btn">
                <button id="label" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">+1 <span class="caret"></span>

                </button>
                <ul class="dropdown-menu" role="menu">
                    <li><a href="#" id="1">US: +1</a>

                    </li>
                    <li><a href="#" id="44">UK: +44</a>

                    </li>
                </ul>
            </div>
            <input class="form-control phone" id="phone" name="phone" aria-label="..." placeholder="Your phone number" type="text"> <span class="input-group-btn">
              <input class="btn btn-default" type="submit">SUBMIT</button>
              </span>

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

and corresponding jQuery:

$('#phone').submit(function (e) {
e.preventDefault();
var phone = $(this).find('.phone').val();

$.ajax({
    url: '/textMessage/' + phone,
    method: "GET",
    success: function () {
        console.log(this);
    }
});

});

$("#1, #44").click(function (e) {
    $("#label").html("+" + $(this).attr("id") + " <span class='caret'></span>");
});
$('.phone').on('input', function (event) {
    this.value = this.value.replace(/[^0-9]/g, '');
});

$("#phone").validate({
    rules: {
        phone: {
            required: true,
            phoneUS: true
        }
    }
});

I can't get the validation to work, and not sure how to use it for UK numbers either.

This is more like what you should be doing. (Note how your ajax() belongs inside of the submitHandler .)

$("#phone").validate({
    rules: {
        phone: {
            required: true,
            phoneUS: true  // start with the default
        }
    },
    submitHandler: function (form) {
        $.ajax({
            url: '/textMessage/' + $('input[name="phone"]').val(),
            method: "GET",
            success: function () {
                console.log(form);
            }
        });
        return false;
    }
});

You cannot apply phoneUS and phoneUK to the same field at the same time since the two regex methods conflict with each other. US phone numbers will be invalid when they're being evaluated for the phoneUK rule.

The solution must be a bit more complicated by using dynamic rule swapping with the .rules('add') and .rules('remove') methods.

var phone = $('input[name="phone"]');

if ($(this).attr("id") == '1') {
    phone.rules('remove', 'phoneUK');
    phone.rules('add', {
        phoneUS: true
    });
} else {
    phone.rules('remove', 'phoneUS');
    phone.rules('add', {
        phoneUK: true
    });
}

(Note, I tried "chaining" the methods to reduce the number of lines but the plugin does not allow .rules() to be chained to .rules() .)

DEMO: http://jsfiddle.net/1a8r5gmv/21/


Fix your broken layout by placing the error message using the errorPlacement option. By default, it's inserted immediately after the input element. Apparently, you need it outside of the element's parent div .

errorPlacement: function(error, element) {
    error.insertAfter($(element).parent('div'));
},

Also, customize the messages with the messages option.

messages: {
    phone: {
        phoneUS: "enter valid US number",
        phoneUK: "enter valid UK number"
    }
},

DEMO 2: http://jsfiddle.net/1a8r5gmv/22/


NOTES :

Invalid HTML here: <input class="btn btn-default" type="submit">SUBMIT</button>

You are closing an <input> tag with a </button> tag.

Should be...

<button class="btn btn-default" type="submit">SUBMIT</button>

OR

<input class="btn btn-default" type="submit" value="SUBMIT" />

Also, in your OP (not in the jsFiddle) you use id="phone" on the <form> element as well as the <input> element. You cannot duplicate any id on a page.


You should not do this...

$(this).find('.phone').val()

The class phone could be more than one element so you should not attach .val() to a group of elements when you want to get the value of one element. Also, when moving this inside of the submitHandler , the $(this) object becomes meaningless. Simply get the value of the field directly.

$('input[name="phone"]').val()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM