javascript to check string in this format

user1513995 picture user1513995 · May 17, 2013 · Viewed 7.6k times · Source

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($component.searchText))
 {
  alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");  

}
}
</script>

Answer

gkalpak picture gkalpak · May 17, 2013

Your 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.