0
function validate() {
  var forename = document.getElementById('forename').value;
  var alpha = /^[a-zA-Z\s]+$/;
  var num = /^[0-9]+$/;
  var space = " ";

  if (forename == "") {
    alert("Please fill out the First Name field.");
    return false;
  }
  if (forename.indexOf(" ") > -1) {
    alert("No spaces are allowed in the First Name field.");
    return false;
  }
  if (forename.value.match(num)) {
    alert("No numbers are allowed in the First Name field.");
    return false;
  }

The above code is part of a validation function for a registration form.

For whatever reason I cannot get my all letters/all numbers if statements to work. Without them the form processes perfectly, however when I start including any value.match argument it breaks the function from that point on. Am I missing anything obvious here?

Goftrey
  • 9
  • 1
  • Possible duplicate of [Check whether an input string contains a number in javascript](https://stackoverflow.com/questions/5778020/check-whether-an-input-string-contains-a-number-in-javascript) – Ivar Dec 03 '18 at 00:18
  • 1
    Your regex only matches if the string contains _only_ numbers. Use `/\d/` instead. – Ivar Dec 03 '18 at 00:19
  • @Ivar Nope that's not it. Even with the string filled with only numbers it still breaks the function. – Goftrey Dec 03 '18 at 00:30
  • `forename.value.match(num)` Remove the `.value`. You already got the value in your `forename` variable. After that [it _does_ match](https://jsfiddle.net/Lgx9tq41/) if your string contains only numbers. – Ivar Dec 03 '18 at 00:42
  • @Ivar Perfect! I can then use that plus an else statement to throw up an error if a letter/number is entered in the field. Thanks for the help. – Goftrey Dec 03 '18 at 01:07

0 Answers0