Greetings, I'm try to do validation on a textbox input to validate a phone number. I have an asp.net textbox and checkbox. The default is to validate a US phone number and when I check the checkbox I should change the RegularExpression and error message to validate an international phone using my own RegularExpression. I have no problem validating the international phone but the problem is when validating the US phone number. I'm always getting an error message that it is invalid phone number. I used different RegularExpression but did not work.
Please look at my code and advise me.
Regards, !
.....................
ASP.net Code
.....................
<%@ Page Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="UpdateContact.aspx.cs" Inherits="IMAM_APPLICATION.UpdateContact" Title="Untitled Page" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script src="js/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="js/jquery.validate.js" type="text/javascript"></script>
<script src="js/js.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
ValidPhoneHome("#<%= chkIntphoneHome%>");
$("#aspnetForm").validate({
// debug: true,
rules: {
"<%=txtHomePhone.UniqueID %>": {
phonehome: true
}
},
errorElement: "mydiv",
wrapper: "mydiv", // a wrapper around the error message
errorPlacement: function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
error.css('top', offset.top - (element.height() / 2));
}
});
})
</script>
<div id="mydiv">
<asp:CheckBox ID="chkIntphoneHome" runat="server" Text="Internation Code"
Style="position: absolute; top: 620px; left: 700px;"
onclick=" ValidPhoneHome(this)" />
<asp:TextBox ID="txtHomePhone" runat="server" Style="top: 650px; left: 700px;
position: absolute; height: 22px; width: 128px" ></asp:TextBox>
</div>
</asp:Content>
.............................
js.js File
...................
var RegularExpression;
var USAPhone = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;
var InterPhone = /^\d{9,12}$/;
var errmsg;
function ValidPhoneHome(sender) {
if (sender.checked == true) {
RegularExpression = InterPhone;
errmsg = "Enter 9 to 12 numbers as international number";
}
else {
RegularExpression = USAPhone;
errmsg = "Enter a valid number";
}
jQuery.validator.addMethod("phonehome", function(value, element) {
return this.optional(element) || RegularExpression.test(value);
}, errmsg);
}