Validate text box so it has 9 numbers and can only start with 9 or 2

Asked

Viewed 82 times

2

Good afternoon,

It needed to create a validation of a text box in which it is mandatory to be only numbers and which must start with 9 or 2 and must also have 9 numbers. Someone gives me a light on how to do?

the form is this :

<div class="form-group">
    <label for="telefone">Telefone: <span id="erro-localidade"></span></label>
    <input type="text" class="form-control" id="telefone" name="telefone">
</div>
<div class="form-group">
    <label for="email">Email address:</label>
    <input type="email" class="form-control" id="email">
</div>
<button type="submit" id="submeterForm1" class="btn btn-default">Enviar</button>

I tried using the match as the friend rray said but the log console always gives me null

<script type="text/javascript">

$( "#submeterForm1" ).click(function(event) {
event.preventDefault();


var telefone = $('#telefone').val();


console.log(telefone.match(/^(9|2)\d{8}$/))

if (telefone.match(/^(9|2)\d{8}$/) == false || telefone == "" || telefone == null) {
    $("#erro-telefone").html("<b style='color:red;'>Por favor preencha o seu telefone correctamente.</b>");
};




}); 

Thank you

  • 1

    If you have more than 9 numbers it validates or says it is invalid?

  • 1

    If you have more than 9 numbers is invalid

1 answer

2


You can use a regular expression to do this,

"988888888".match(/^(9|2)\d{8}$/);

^ sets which characters should be at the beginning of the line in this case 9 or 2 ((9|2) pipe acts as an OR/OR) that is followed by 8 digits(0-9), who defines the quantity is the number between the keys ({8})

Or alternatively:

"212345678".match(/^[29]\d{8}$/);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.