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

2

Good afternoon,

I needed to create a validation of a text box in which it is mandatory to be only numbers and that it must begin with 9 or 2 and also have 9 numbers. Someone gives me a light 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 friend rray said but in the console log 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

    
asked by anonymous 26.07.2016 / 16:42

1 answer

2

You can use a regular expression to do this,

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

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

Or alternatively:

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