Approach 1
If you're OK with putting some of your logic in your JavaScript, something as simple as this function should do :
function validate(teststring) {
return teststring.match(/\d/g).length < 8;
}
Demo
function validate(teststring) {
return teststring.match(/\d/g).length < 8;
}
document.body.innerHTML =
'<b>abcd1234ghi567 :</b> ' + validate('abcd1234ghi567') + '<br />' +
'<b>1234567abc :</b> ' + validate('1234567abc') + '<br />'+
'<b>ab1234cd567 :</b> ' + validate('ab1234cd567') + '<br />'+
'<b>abc12 :</b> ' + validate('abc12') + '<br />'+
'<b>abc12345678 :</b> ' + validate('abc12345678') + '<br />';
(see also this Fiddle)
Approach 2
If you prefer all of your logic to be in your regex instead of your JavaScript, you could use a regex like /^(\D*\d?\D*){7}$/
or /^([^0-9]*[0-9]?[^0-9]*){7}$/
and use RegExp.prototype.test() instead of String.prototype.match() to test your strings.
In that case, your validate function would look something like this :
function validate(teststring) {
return /^([^0-9]*[0-9]?[^0-9]*){7}$/.test(teststring);
}
Demo :
function validate(teststring) {
return /^([^0-9]*[0-9]?[^0-9]*){7}$/.test(teststring);
}
document.body.innerHTML =
'<b>abcd1234ghi567 :</b> ' + validate('abcd1234ghi567') + '<br />' +
'<b>1234567abc :</b> ' + validate('1234567abc') + '<br />'+
'<b>ab1234cd567 :</b> ' + validate('ab1234cd567') + '<br />'+
'<b>abc12 :</b> ' + validate('abc12') + '<br />'+
'<b>abc12345678 :</b> ' + validate('abc12345678') + '<br />';