Pregunta

Currently I have a piece of javascript that stops the form been submitted if the inputs are empty but I want to make the script also stop non-alphabetical characters been put in too.

Here is the script

`function checkFormWhole(){

        //var theForm = document.getElementById(id);
        var letters = /^[A-Za-z]+$/;
        var letnums = /^[A-Za-z0-9]+$/;
        var theForm = document.getElementById("bookingForm");


            if (theForm.customerType.value == ""){
                alert("Please choose a customer type");
                return false;

                        }
            else if (theForm.customerType.value == "nonCorp" && theForm.forename.value == "") {
                    alert("Please Enter A Forename");
                    return false;

            }
            else if (theForm.customerType.value == "nonCorp" && theForm.surname.value == "") {
                    alert("Please Enter A Surname");
                    return false;

            }
            else if (checked == 0) {
                    alert("Please Choose An Event To Book");
                    return false;

            }
            else if (theForm.customerType.value == "corp" && theForm.companyName.value == "") {
                    alert("Please Enter A Company Name");
                    return false;

            }

where i want the validation --->

else if (theForm.customerType.value == "nonCorp" && theForm.forename.value != (letters)  /*|| theForm.customerType.surname.value.match != (letters)*/) {
                        alert("Please Enter A Forename Containing ONLY letters");
                        return false;
                }


                        }`
¿Fue útil?

Solución

You need to use the pattern as below.

var str = '123456';
var str2 = 'abcdEFG';
var patt = /[^a-zA-Z]/g;
// Contains non alphabet chars
if(patt.test(str) === true) {
    console.log('Your input includes invalid characters')
}

// Contains alphabet chars only
if(patt.test(str2) === false) {
    console.log('Your input includes valid characters')
}

You can simplify this but the example above has enough for you to be able to add the functionality you need.

Add your example to jsfiddle and if you have any problems, people can help you easier.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top