简体   繁体   中英

Javascript Validation not Working with Regular expression

My javascript validator is not working. When I input nothing, the alert is not displayed. Additionally, could you guys explain to me what the action method regarding forms is and how I am supposed to use it?

<form method = "post" id = "my_form">
        <h1> Thank you for visiting our website! Please take some time to fill out our service questions! </h1>
        <h2> The ratings given are F, D, C, B and A. </h3>
        <h3> How would you rate the service that this webpage provides?? </h3> 
        <input type = "text" font-size = "15px" id = "name">
        <h3> How would you rate the organization and usability of this webpage?? </h3> 
        <input type = "text" font-size = "15px" id = "name">
        <h3> How would you rate the professionalism of this webpage?? </h3> 
        <input type = "text" font-size = "15px" id = "name">
        <h3> How would you rate the overall look of this webpage??</h3> 
        <input type = "text" font-size = "15px" id = "name">
        <br /><br />
        <input type = "submit" id = "submit" value = "submit" name = "submit">
        </form>

<script type = "text/javascript">
var my_form = document.getElementById("my_form");
my_form.addEventListener("submit", function(event) {
    var name = document.getElementById("name").value;
    var tomatch = /[a-f]/i;
    if (!tomatch.test(name)) {
    event.preventDefault();
    window.alert("The name can only contain letters from a-f");
    }
}. false);
</script>

You have several inputs with same ID, and incorrect syntax error here

my_form.addEventListener("submit", function(event) {
    // bunch of code...
}. false); // <-- not dot, but comma

Check the solution below

 document.getElementById("my_form").onsubmit = function(event) { var tomatch = /[af]/i; //var name = document.getElementById("name").value; // you can also get value like this var name = document.forms.my_form.name.value if (!tomatch.test(name)) { event.preventDefault(); window.alert("The name can only contain letters from af"); } } 
 <form method="post" id="my_form" method="post" action"/my-url"> <input type="text" font-size="15px" id="name"> <input type="submit" id="submit" value="submit" name="submit"> </form> 

For regular expression use

var tomatch = new RegExp("/[a-f]/i");

Regards.

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