i want javascript code to check whether my input text is in specific format as AS0301-12345
<apex:inputText id="searchText" value="{!searchText}" onmousemove="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var pattern = "([a-zA-Z](2)[0-9](4)-[0-9](5))"; /// is it correct
var regexp = new System.Text.RegularExpressions.Regex(pattern);
var userInput = "(123) 555-1243";
if (!regexp.IsMatch($ponent.searchText))
{
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
i want javascript code to check whether my input text is in specific format as AS0301-12345
<apex:inputText id="searchText" value="{!searchText}" onmousemove="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var pattern = "([a-zA-Z](2)[0-9](4)-[0-9](5))"; /// is it correct
var regexp = new System.Text.RegularExpressions.Regex(pattern);
var userInput = "(123) 555-1243";
if (!regexp.IsMatch($ponent.searchText))
{
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
Share
Improve this question
asked May 17, 2013 at 20:06
user1513995user1513995
231 silver badge3 bronze badges
4
- 3 Javascript is not C#. And, your regex is wrong; you need braces. – SLaks Commented May 17, 2013 at 20:07
-
Also,
onmousemove
is probably not the best event handler to call that function with.. – Mike Christensen Commented May 17, 2013 at 20:15 - Hi MIke, how about using onfocus? – user1513995 Commented May 17, 2013 at 20:26
-
onblur
oronchange
might be better, since you want to validate the input after it changes.. – Mike Christensen Commented May 17, 2013 at 20:52
2 Answers
Reset to default 4Your JS function should look more like this:
function checkingstring(inputElem) {
var regex = /^[A-Z]{2}[0-9]{4}-[0-9]{5}$/i;
var searchText = inputElem.value;
if (searchText.length && !regex.test(searchText)) {
alert('The syntax is always as follows: AANNNN-NNNNN \n' +
'(A: Alpha/Letter; N: Number), e.g. FL0301-12345');
}
}
You should probably also change the onmousemove
to something more meaningful, like onblur
maybe.
Take a look at this short demo.
This is how I'd do it. There is a lot of functionality you can squeeze into shorthand. Changed onMouseMove to onChange so instead of checking whenever the mouse moves it should check when an edit of searchText pletes.
<apex:inputText id="searchText" value="{!searchText}" onChange="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var regexp = /^[A-Z]{2}\d{4}-\d{5}$/i; //AANNNN-NNNNN A = Capital N = Number
if (!regexp.exec(searchText.value)) {
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
got some ideas from w3schools js regexp page.