Search code examples
javascriptsalesforceapex-codevisualforcesalesforce-service-cloud

javascript to check string in this format


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>

Solution

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