-4

The subject exists but I don't understand here: (I am beginner)

Check whether a string matches a regex in JS

In fact, I have a form name, in my validation I would like to avoid that the user enters numbers or symbols.

function validation()
{
    const name = document.getElementById('name').value;

    if(!name){
        document.getElementById('nameError').innerHTML = " ** Empty ! ";
        return false;
    }


}
<form action="#" onsubmit="return validation()" >
  <br>
  <label>Name </label>
  <br>
  <input type="text" name="name" id="name" placeholder="Your name">
  <br>
  <span id="nameError"></span>
  <br>
  <input type="submit" value="ok">
</form>

Thank you very much for your help.

  • Have you attempted to create a regex yourself? Even if it isn't working, it's easier and more helpful to future visitors to explain why your attempt isn't working, rather than writing the code for you, so it would be good if you could add it to your question. – Run_Script Jun 01 '20 at 11:22

3 Answers3

2

function validation() {
  const name = document.getElementById('name').value;

  if (!name) {
    document.getElementById('nameError').innerHTML = ' ** Empty ! ';
    return false;
  }

  if (!/^[a-zA-Z]+$/.test(name)) {
    document.getElementById('nameError').innerHTML = ' ** No number or symbol ! ';
    return false;
  }
}
<form action="#" onsubmit="return validation()" >
  <br>
  <label>Name </label>
  <br>
  <input type="text" name="name" id="name" placeholder="Your name">
  <br>
  <span id="nameError"></span>
  <br>
  <input type="submit" value="ok">
</form>
Treast
  • 1,095
  • 1
  • 9
  • 20
1

In your validation function, you can verify if the variable name contains only characters using a regex.

Please check the snippet below:

function validation() {
    const letters = /^[A-Za-z]+$/;
    const name = document.getElementById('name').value;
    if (name.match(letters)) {
        // contains only characters
    } else {
        // contains non-character values
    }
}
0

Try

if(/^([a-zA-Z ]+)$/.test(name) === false) {
 ... // Your error handle code
}
Rafik Farhad
  • 1,182
  • 2
  • 12
  • 21