Question

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>
Was it helpful?

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top