I need to validate a field and it must have the following format: two_leths / numbers. Ex .: RN / 1234567. The two letters will always be uppercase and the number of numbers has no limit.
I need to validate a field and it must have the following format: two_leths / numbers. Ex .: RN / 1234567. The two letters will always be uppercase and the number of numbers has no limit.
I'm not very good at Regex, but I think this one is for you:
[A-Z]{2}[\/][0-9]{1,}
Explanation:
[A-Z]{2}
: Find two characters from A to Z [\/]
: Find a bar [1-9]{1,}
: Finds from 1 to infinite numbers In general, if you want to validate if there are two letters, uppercase, followed by a slash and then only numbers, no specific size can use:
[A-Z]{2}\/[0-9]{1,}
This will make it valid for the characters between A and Z. Then a bar, escaped, to require the bar after the two letters. Then check for numbers between 0 and 9, at least there must be a number to infinity.
One solution: str.match(/\w{2}\/\d+/g)
\w{2}
any letter ( w ord) 2 times \/
a bar /
\d+
any digit ( d igit) 1 or more times To complement the above answers, to use the regular expression explained above you can do as follows:
PHP
$codigo = 'RN/1234567';
$regex = '~[A-Z]{2}\/[1-9]{1,}~';
if (preg_match($regex, $codigo)) {
echo 'Código válido!';
} else {
echo 'Insira um código válido!';
}
JavaScript
var codigo = 'RN/1234560';
var regex = /[A-Z]{2}\/[1-9]{1,}/g;
if (regex.test(codigo)) {
console.log('Código válido!');
} else {
console.log('Insira um código válido!');
}
With Javascript, you can do so:
function validarMeuCampo(texto) {
var captura = texto.match(/[A-Z][A-Z]\/[0-9]+/);
var valido = !!captura && captura.length == 1 && captura[0].length == texto.length;
return valido;
}
Explanation:
The regular expression /[A-Z][A-Z]\/[0-9]+/
captures two uppercase letters, followed by a forward slash, followed by a number of numbers. The number of numbers is unlimited, but there must be at least one number (this is what the +
to the right of the numbers does).
The method match
of type String receives a regular expression and returns an array of portions of the String for which the expression encountered something. If it does not find anything, it returns null.
The !
operator negates. It happens that in everything Javascript is deniable. Deny twice is a way of finding out if a variable that should be an object has value, since the negation of an object is false, and the negation of null is true. In other words: the opposite of my opposite is a Boolean value that tells me whether I have value or not.
Putting everything together: find in the text informed passages that hit the regular expression. If you find a single result that is equal to the string, then the string is valid for your rule.