RegEx for matching UK Postcodes

前端 未结 30 2436
广开言路
广开言路 2020-11-22 01:38

I\'m after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For in

30条回答
  •  一生所求
    2020-11-22 02:05

    Below method will check the post code and provide complete info

    const valid_postcode = postcode => {
        try {
            postcode = postcode.replace(/\s/g, "");
            const fromat = postcode
                .toUpperCase()
                .match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
            const finalValue = `${fromat[1]} ${fromat[2]}`;
            const regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i;
            return {
                isValid: regex.test(postcode),
                formatedPostCode: finalValue,
                error: false,
                info: 'It is a valid postcode'
            };
        } catch (error) {
            return { error: true , info: 'Invalid post code has been entered!'};
        }
    };
    
    valid_postcode('GU348RR')
    result => {isValid: true, formatedPostCode: "GU34 8RR", error: false, info: "It is a valid postcode"}
    
    valid_postcode('sdasd4746asd')
    result => {error: true, info: "Invalid post code has been entered!"}
    
    valid_postcode('787898523')
    result => {error: true, info: "Invalid post code has been entered!"}
    

提交回复
热议问题