Reputation: 25
I have a form with a phone mask, but I can’t make a red borderColor
when all the phone numbers are not filled and green when everything is correct.
HTML
<form id="border1">
<input type="text" placeholder="Phone number" class="phone_mask">
</form>
<button id="button" class="form-button" onclick="checkNum(document.querySelector('.phone_mask'))">
Sign up
</button>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/jquery.maskedinput.js"
type="text/javascript"></script>
CSS
.phone_mask {
border: 2px solid #eef0ef;
border-radius: 3px;
height: 41px;
width: 327px;
margin: 30px 0px 0px 19px;
padding-left: 12px;
outline: none;
}
.phone_mask:focus {
border: 2px solid #bdd9f7;
border-radius: 2px;
box-shadow: 0px 0px 2px 3px #bdd9f7;
height: 41px;
width: 327px;
outline: none;
}
JS
let phoneBlock = document.querySelector('.phone_mask')
let phone = $(".phone_mask").mask("+38(099)999-99-99");
function checkNum() {
if (!phone) {
phoneBlock.style.borderColor = 'red';
}
else {
phoneBlock.style.borderColor = 'green'
}
}
Help me please, thanks!
Upvotes: 0
Views: 1078
Reputation: 452
the pattern property in HTML input tags is your friend here
The pattern is a regular expression, you could also use stuff like \w
for word characters and \d
for digits
for more about REGEX check this cheat sheet
don't forget to escape parenthesis , braces or point with a \ if you need them
in CSS you can use the :valid
and :invalid
selectors to style the different states of your inputs
the :invalid
selector won't kick in unless your user clicks submit with invalid data in the targeted input
Upvotes: 0
Reputation: 665
You don't need to use JavaScript for validating a phone pattern.
Instead, use input attribute pattern
for validating a pattern and then adding a border to a valid pattern with pseudo-class :valid
Pattern in my code should be +38-999-99-999
.phone_mask {
border: 2px solid #eef0ef;
border-radius: 3px;
height: 41px;
width: 327px;
margin: 30px 0px 0px 19px;
padding-left: 12px;
outline: none;
}
.phone_mask:focus {
border: 2px solid #bdd9f7;
border-radius: 2px;
box-shadow: 0px 0px 2px 3px #bdd9f7;
height: 41px;
width: 327px;
outline: none;
}
.phone_mask:valid {
border: 2px solid limegreen;
}
<form id="border1">
<input type="tel" placeholder="Phone number" class="phone_mask"
pattern="[+]{1}[3]{1}[8]{1}-[0-9]{3}-[0-9]{2}-[0-9]{3}" required>
<button id="button" class="form-button" onclick="">Sign up</button>
</form>
For telephone numbers use type="tel"
.
pattern
attribute in a nutshell:[]
) to specify what character (or range of characters should be there) - [1-9]
/[+]
/[9]
{}
) to specify how many of those characters should be there - {1}
, {2}
etc.-
or /
)If you strictly want to use .mask
jQuery, here you go:
Phone mask with jQuery and Masked Input Plugin
Learn more:
Pattern attribute and input types
Upvotes: 1