This is the code
let first = document.getElementById('name');
function check() {
var pattern = /^[a-zA-Z]+$/;
var res = pattern.test(first.value);
if (first.value != res) {
alert('Invalid First Name');
}
}
<div class="form-group">
<input id="name" type="text" placeholder="Name" name="name"></div>
<button type="submit" class="btn btn-primary signupbtn" onclick="check()">
Sign Up
</button>
I have tried keeping (first.value = res) and then executing. This time it is giving alert message only when there is correct input but not when wrong input. But as keep (first.value != res) then it is showing error message every time I press the signup button.
The .test() method returns a boolean. You just need to check if the value matches the regex if not you can run the alert.
let first = document.getElementById('name');
function check() {
var pattern = /^[a-zA-Z]+$/;
var res = pattern.test(first.value);
console.log(first.value)
if(!res){
alert('Invalid First Name');
}
}