我希望javascript代码检查我的输入文字是否为特定格式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>
答案 0 :(得分:4)
你的JS函数看起来应该更像这样:
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');
}
}
您可能还应该将onmousemove
更改为更有意义的内容,例如onblur
请看一下 short demo 。
答案 1 :(得分:0)
我就是这样做的。有很多功能可以用来缩写。将onMouseMove更改为onChange,以便在鼠标移动时检查它,而不是检查searchText的编辑何时完成。
<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>
从w3schools js regexp页面获得了一些想法。