I’m creating a validation on input fields. Its validation is a "8 Characters minimum" and "only contains a combination of letters and numbers".
I’ve made the script as below but it’s still not what I want. Currently, the errors that appear are one by one, not all at once.
For example, if I type "a12" it should show a "8 characters minimum" error. and if I type "a12." or "a12@" , the "8 character minimum" error will disappear and only show "only contains a combination of letters and numbers" error.
The error should be 8 character minimum, only contains a combination of letters and numbers
how to solve this?
$("[name='testing']").on('keyup', function(){
const getValue = $(this).val();
const numbers = /^[A-Za-z0-9]*$/;
if(getValue.length < 8){
$('.error').html('<span class="min-char">8 character minimum</span>')
if(getValue.match(numbers)){
$('.error .combine-pass').remove()
}else{
$('.error').html('<span class="combine-pass">Combination of letters and numbers</span>')
}
}else{
$('.error .min-char').remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="testing">
<div class="error"></div>
2
Answers
I used regular expression validation and javascript event listeners to implement the use case.
Please upvote if you find this answer useful.
If you want to check input text contains special character/s then use regex:
rg1 = /[^a-z0-9]/gi
.If you want to check input text contains exactly 8 charcters (letters & numbers) then use regex:
rg2 = /^[a-z0-9]{8}$/gi
using this two regex you can clearly validate your input and so output accordingly.
Don’t require the length validation. If the input text length is exactly 8, then
rg2
returntrue
otherwisefalse
.