In this article I will explain with an example, how to use Regular Expression (Regex) to allow only Numbers (Digits) and Special characters in JavaScript and jQuery.
Regular Expression to allow only Numbers and Special characters in JavaScript
The following HTML Markup consists of a TextBox, a Button and an HTML SPAN. On the OnClick event of the Button, a JavaScript function is executed which validates the TextBox text against the Regular Expression (Regex) and if it contains character other than Numbers (Digits) or the specified Special characters then an error message is displayed.
<input type="text" id="TextBox1" />
<br />
<span id="spnError" style="color: Red; display: none">*Valid characters: Numbers and special characters.</span>
<br />
<input type="button" value="Validate" onclick="return Validate()" />
<script type="text/javascript">
function Validate() {
var isValid = false;
var regex = /^[0-9-+()]*$/;
isValid = regex.test(document.getElementById("TextBox1").value);
document.getElementById("spnError").style.display = !isValid ? "block" : "none";
return isValid;
}
</script>
Regular Expression to allow only Numbers and Special characters in jQuery
The following HTML Markup consists of a TextBox, a Button and an HTML SPAN. To the Button a jQuery click event handler is attached thus when the button is clicked, the TextBox text is validated against the Regular Expression (Regex) and if it contains character other than Numbers (Digits) or the specified Special characters then an error message is displayed.
<input type="text" id="TextBox1" />
<br />
<span id="spnError" style="color: Red; display: none">*Valid characters: Numbers and special characters.</span>
<br />
<input type="button" id="btnValidate" value="Validate" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnValidate").click(function () {
var isValid = false;
var regex = /^[0-9-+()]*$/;
isValid = regex.test($("#TextBox1").val());
$("#spnError").css("display", !isValid ? "block" : "none");
return isValid;
});
});
</script>
Screenshot
Demo
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads