This is the code
<div ><input id="name" type="text" placeholder="Name" name="name" ></div> <button type="submit" onclick="check()">Sign Up</button>
`
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');
}
}
`
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.
CodePudding user response:
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');
}
}