简体   繁体   中英

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.");
    }
  }
})

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;
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM