pdf javascript validate field contains part of pure letter and pure numbers only

Viewed 31

I want to check if Field1 is in the format of XXXX-0YYYY or XXXX-1YYYY where XXXX are letters only and YYYY are digits only note that after XXXX it should start with "-0" or "-1" only

I made the following code and it didn't work as expected:

var string = this.getField("Field1").value;
var string1 = string.substring(0, 4);
var string2 = string.substring(5, 10);

var n1 = event.value.indexOf("-0",4);
var n2 = event.value.indexOf("-1",4);
var n3 = n1 + n2

var isLetter = /[^a-zA-Z]/.test(string1);
var isNum = /^\d+$/.test(string2);

if ( !isLetter || n3 < -1 || !isNum ) { // incorrect format
    app.alert("ERROR MESSAGE");
    event.rc = false;
}
else {
    event.rc = true;
}
1 Answers

You can use a Regular Expression to achieve that, I made some tests in the RegExr website, it's a great tool to validade your regexes. I got this result:

function validateField(value) {
  return /^[A-Za-z]{4}-(0|1)\d{4}$/.test(value);
}

// Testing
console.log(['AAAA-09999', 'AAAA-19999', 'A1AA-0999Z', 'AAAA-29999', 'ZZZ-09999'].map(e => `${e} ${validateField(e) ? 'is' : 'is not'} a valid field`).join('\n'));

Related