Regex Checking for Numbers in the input field
Check for values that match a Regex pattern in the input field. Push a button and apply the match checker to return the results in the console.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div class=”main”>
<input id=”nums” ><button>Submit</button>
</div>
<script>
const nums = document.querySelector(‘#nums’);
const btn = document.querySelector(‘button’);
btn.onclick = ()=>{
const pattern = /^[0-9]*$/gm;
const results = nums.value.match(pattern);
const isValidNumber = results != null;
console.log(isValidNumber);
}
</script>
</body>
</html>
/^[0-9]*$/g = Only numbers in the string
/[0-9]+/g = Will return numbers in the result ignore non digits 0-9
/[\D]/g = Every Character other than digits
/\d/g = Digits separated