Add Class if it matches a pattern

Asked

Viewed 49 times

3

I’m trying to get you to add a Class is an element through its ID if it is a certain kind of pattern.

if (/^([0-9]{4}[\-]?[0-9]{3})$/.test('#codigoPost')) {
  $('#codigoPost').removeClass("is-invalid");
  $('#codigoPost').addClass("is-valid");
} else {
  $('#codigoPost').removeClass("is-valid");
  $('#codigoPost').addClass("is-invalid");
}
.is-valid(
border: 1px solid red;
)

.is-invalid(
border: 1px solid green;
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div>
    <label class="label-noPadding" for="codigoPost">Código Postal</label>
    <input type="number" class="form-control" name="codigoPost" id="codigoPost" pattern="[0-9]{4}[\-]?[0-9]{3}" placeholder="0000-000" required="true">
  </div>
</form>

Basically, if it is of the genus "1234-123", "2222-333" or "9876-543". 4 numbers, followed by a "-" and followed by 3 numbers add to class. But I don’t see what I’m doing wrong here, he always gives false entering the else. I would appreciate your help.

  • puts the rest of the html too if it is not impossible to test your snippet because there is no element with this #id

  • 1

    @Lodi So it gets better?

1 answer

4


I put the function in the event of onkeyup, I switched the guy from input was number for text.
Motive: Like number every time a character other than a number enters, the value of the input, how do you expect a - can’t be number.
I hit the style who was with () instead of {} and put the color red on invalid and the green in the valid, took the outline of input to see better in the snippet

function teste(){
    var self = $(this),
        valor = self.val(),
        result_teste = /^([0-9]{4}[\-]?[0-9]{3})$/.test(valor);
    console.log( valor, result_teste );
    if ( result_teste ) {
      self.removeClass("is-invalid").addClass("is-valid");
    } else {
      self.removeClass("is-valid").addClass("is-invalid");
    }
 }

 $('#codigoPost').on('keyup',teste);
input{ outline:none; }
.is-valid{
border: 1px solid green;
}

.is-invalid{
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div>
    <label class="label-noPadding" for="codigoPost">Código Postal</label>
    <input type="text" class="form-control" name="codigoPost" id="codigoPost" pattern="[0-9]{4}[\-]?[0-9]{3}" placeholder="0000-000" required="true">
  </div>
</form>

  • 1

    Thank you very much I think my biggest problem was having the guy like number and not as text but I simplify the code with this thank you very much :)

Browser other questions tagged

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