jQuery validation plugin: accept only alphabetical characters?

前端 未结 6 2301
-上瘾入骨i
-上瘾入骨i 2020-11-29 02:37

I\'d like to use jQuery\'s validation plugin to validate a field that only accepts alphabetical characters, but there doesn\'t seem to be a defined rule for it. I\'ve search

6条回答
  •  不知归路
    2020-11-29 02:59

    Be careful,

    jQuery.validator.addMethod("lettersonly", function(value, element) 
    {
    return this.optional(element) || /^[a-z," "]+$/i.test(value);
    }, "Letters and spaces only please"); 
    

    [a-z, " "] by adding the comma and quotation marks, you are allowing spaces, commas and quotation marks into the input box.

    For spaces + text, just do this:

    jQuery.validator.addMethod("lettersonly", function(value, element) 
    {
    return this.optional(element) || /^[a-z ]+$/i.test(value);
    }, "Letters and spaces only please");
    

    [a-z ] this allows spaces aswell as text only.

    ............................................................................

    also the message "Letters and spaces only please" is not required, if you already have a message in messages:

    messages:{
            firstname:{
            required: "Enter your first name",
            minlength: jQuery.format("Enter at least (2) characters"),
            maxlength:jQuery.format("First name too long more than (80) characters"),
            lettersonly:jQuery.format("letters only mate")
            },
    

    Adam

提交回复
热议问题