验证仅用于字母输入的表单

时间:2011-08-04 15:52:02

标签: javascript

我验证了一个表单但是我很难让它只接受firstname和lastname字段的字母

希望你能帮忙

继承我的代码:

$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
onlyletters = "Only letters allowed.";

$("#theform").submit(function(){    
    //Validate required fields
    for (i=0;i<required.length;i++) {
        var input = $('#'+required[i]);
        if ((input.val() == "") || (input.val() == emptyerror)) {
            input.addClass("needsfilled");
            input.val(emptyerror);
            errornotice.fadeIn(750);
        } else {
            input.removeClass("needsfilled");
        }
    }


        // Only Letters.
    if (!/^([a-zA-Z])+$/.test(errornotice.val())) {
        errornotice.addClass("needsfilled");
        errornotice.val(onlyletters);
    }


    // Validate the e-mail.
    if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
        email.addClass("needsfilled");
        email.val(emailerror);
    }

    //if any inputs on the page have the class 'needsfilled' the form will not submit
    if ($(":input").hasClass("needsfilled")) {
        return false;
    } else {
        errornotice.hide();
        return true;
    }
});

// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){       
   if ($(this).hasClass("needsfilled") ) {
        $(this).val("");
        $(this).removeClass("needsfilled");
    }
});
}); 

1 个答案:

答案 0 :(得分:1)

此行应该针对errornotice.val()还是firstname.val()进行测试?

if (!/^([a-zA-Z])+$/.test(errornotice.val())) {

// Maybe this is what you intended.
// This requires adding some more variables earlier when you set email and errornotice
email = $("#email");
errornotice = $("#error");
// Add vars for first/lastname
firstname = $("#firstname");
lastname = $("#lastname");

if (!/^([a-zA-Z])+$/.test(firstname.val())) {
    firstname.addClass("needsfilled");
    firstname.val(onlyletters);
}
// then do the same for lastname
if (!/^([a-zA-Z])+$/.test(lastname.val())) {
    lastname.addClass("needsfilled");
    lastname.val(onlyletters);
}

然而,你的正则字母只能消除许多有效的名字,包括撇号,变音符号,变音符号等。