简体   繁体   中英

My regex javascript validation doesn't seem to be working

I'm trying to validate a textbox to see if it contains numbers and special characters, but for some reason, my code doesn't seem to work:

<script>
    function validation(){
        var firstname = $("#Fname").val();
        if(firstname.match(/^[A-Za-z]*/)){
            return true;
        }
        else{
            alert("Invalid name!");
            return false;
        }
    };
</script>

And here is where I called the function:

<form method="POST" action="confirmReservation.php" onSubmit="return validation()" name ="frm">
    <div class="col-md-2 form-group">
        <br><input type="text" id = "Fname" name="Fname" class="form-control"  placeholder="First Name" required>
    </div>
</form>

What might be the problem in my code?

You can do as following using jquery:

var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
   alert('Your search string contains illegal characters.');
}

Reference from this post

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