JavaScript Field validater

The following is a validate which use Javascript regularexpress to implement. The part to revoke javascript function is “ onchange=”regcheckTimeSeconds(this);

The regular express patter could find at the site: http://www.regexlib.com/Search.aspx?k=&c=5&m=-1&ps=100&AspxAutoDetectCookieSupport=1

Front page code.

<asp:TemplateField HeaderText="From">
	<FooterStyle HorizontalAlign="Right" />
	<HeaderStyle HorizontalAlign="Left" Width="120px" />
	<ItemStyle CssClass="" HorizontalAlign="Left" Width="120px" VerticalAlign="Top" />
	<ItemTemplate>
		<asp:Button ID="btnTime1" Text="T" runat="server" OnClick="gdEdit_TimeSet" />
		<asp:Button ID="btnTime2" Text="-" runat="server" OnClick="gdEdit_TimeSet" />
		<asp:Button ID="btnTime3" Text="+" runat="server" OnClick="gdEdit_TimeSet" />
		<br />
		<asp:TextBox ID="txtTimeFrom" Width="80px" Text='<%# Eval("TimeStart", "{0:T}").ToString.ToLower %>' onchange="regcheckTimeSeconds(this);" AutoPostBack="false" TabIndex="20" runat="server" />
	</ItemTemplate>
</asp:TemplateField>

 

JavaScript code


	function regcheckTimeSeconds(txtbox) {
        var s = txtbox.value
        //var reg = new RegExp("^((([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?))$");
        //var reg = new RegExp("^((([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?))$");

        // var reg = new RegExp("^([1-9]|1[0-2]|0[1-9]){1}(:[0-5][0-9](\:[0-5][0-9]\s?[aApP][mM])){1}$");
        var reg = new RegExp("^(1[0-2]|[1-9]):[0-5][0-9]:[0-5][0-9][ ]?[aApP][mM]$");

	    if ((/^\s*$/).test(s)) {
        }
        else{
            if (String(s).search(reg) == -1) {
                txtbox.style.color = "red";
                alert("The time format is incorrect.\r\n\r\nThe correct format is:\r\nHH:MM:SS am/pm\r\n\r\nFor example:\r\n11:41:55 pm");
            } else {
                txtbox.style.color = "black";
            }
	    }

	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s