Javascript RegEx partial match

后端 未结 6 1849
轮回少年
轮回少年 2021-01-04 03:20

I have a regular expression pattern, which validates for a three digit number

/^\\d{3}$/.test(\"123\")   // true
/^\\d{3}$/.test(\"123.\")  // false
<         


        
相关标签:
6条回答
  • 2021-01-04 03:34

    You can specify a range in the expression so that it matches anything between one and three digits like so:

    /^\d{1,3}$/.test("1")  // true
    /^\d{1,3}$/.test("12")  // true
    /^\d{1,3}$/.test("123a")  // false
    
    0 讨论(0)
  • 2021-01-04 03:40

    According to your last edit, this should work:

    /^#[a-fA-F0-9]{0,6}$/
    
    0 讨论(0)
  • 2021-01-04 03:46

    You would be better off by using a library like maskedinput.js. You can then setup your text input like follows:

    jQuery(function($){
        $("#your_input").mask("999");
    });
    

    UPDATE

    you can use a validator for forms and preset specific types of fields to validate

    0 讨论(0)
  • 2021-01-04 03:51

    Just provide a regex that allows for partial matches. e.g. /^\d{1,3}$/

    0 讨论(0)
  • 2021-01-04 03:57

    You could partially validate the email address by using ()? for more letters and/or characters. Every ()? going deeper in the validation tree.

    The following regular expression pattern validates email address letter by letter.

    ^[a-zA-Z]+(@{1}[a-zA-Z]*(\.{1}[a-zA-Z]*)?)?$
    

    It does not take into account every possibility out there, but for basic ones like aa@bb.dd it works just fine and there's room to improve it further.

    0 讨论(0)
  • 2021-01-04 03:59

    You'll want to use explicit "|" partial matches. For your color matching example it's pretty simple, you just need to explicitly match an empty string partial

    /^(|#[a-f0-9]{0,6})$/i.test(inputStr)
    

    For an email it's more complicated since there are more partial match combinations

    /^(|\w+|\w+@|\w+@\w+|\w+@\w+\.|\w+@\w+\.\w+)$/.test(inputStr)
    

    Note that you can't get away with something like /^(|\w*@|...)$/ since that matches @blah.com which isn't a valid partial input.

    0 讨论(0)
提交回复
热议问题