< input class =required-inputid =ssntype =textname =ssnplaceholder =123-45-6789onBlur =myFunc()>
还有另一种强制用户始终输入该模式的方法 -
< input class =required-inputid =ssntype =textname =ssnplaceholder =123-45-6789onBlur =myFunc()required pattern =\d {3} [\-] \d {2} [\-] \d {4}>
I have this sample:
link
CODE HTML:
<input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789">
CODE CSS:
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
CODE JS:
function ssnFormat(){
$("#ssn").on('blur change', function () {
text = $(this).val().replace(/(\d{3})(\d{2})(\d{4})/, "$3-$2-$4");
if ($(this).val() == '' || $(this).val().match(text) || $(this).val().length == 0) {
$(this).removeClass('valid').addClass('invalid');
}else {
$(this).removeClass('invalid').addClass('valid');
}
});
}
$( "#ssn" ).on('blur change', function() {
ssnFormat();
});
What I want to do these things are:
1.If I write the following text I want to validate this format 123-12-1234
2.If I write 123456789
I want to transform when click outside input in this format
123-12-1234
I tried to do this by using the function below but don't work
$("#ssn").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,''); //here is a problem
$(this).val(value);
});
Can you please help me solve this problem?
Thanks in advance!
解决方案
Try this
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
Also there is another way to enforce user always enters that pattern -
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()" required pattern="\d{3}[\-]\d{2}[\-]\d{4}">
这篇关于社会安全号码输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!