Kempster
Kempster

Reputation: 49

JSFiddle basic form validation with regex not working

https://jsfiddle.net/gzLeLjmb/

For some reason JSFiddle is throwing an error and I can't work out why? I'm just trying to validate an input with a regex for a persons name.

$("document").ready(function() {
  function validateForm() {
    var userName = $("input[name=userName]").val();
    var subject = $("input[name=subject]").val();
    var message = $("input[name=message]").val();

    if (/^[a-zA-Z ]{2,30}$/.test(userName)) {
      alert("Your name is in the correct format");
    } else {
      alert("Your name can't contain numbers or other characters etc.");
    }
  }
})

Upvotes: 0

Views: 653

Answers (1)

ZeroCho
ZeroCho

Reputation: 1360

Everything looks fine to me, except that you should use return false to prevent form from submitting formData.

Also separating javascript logic from the html is recommended.

$("document").ready(function(){
    $('form').on('submit', function() {
        var userName = $("input[name=userName]").val();
        var subject = $("input[name=subject]").val();
        var message = $("input[name=message]").val();
        if (/^[a-zA-Z ]{2,30}$/.test(userName)) {
             alert("Your name is in the correct format");
        }
        else{
            alert("Your name can't contain numbers or other characters etc.");
            return false;
        }
    });
});

Upvotes: 1

Related Questions