简体   繁体   中英

regular expression for entering wrong address and restrict user using javascript or jQuery

I tried the piece of code to restrict user if the address is wrongly entered as shown below sample address: #23 78/54, A-31 Nand Jyot Indl Estate, Andheri- Kurla Road, Saki Naka ( allowed )

14/18, Loha Bhavan, PD Mello Rd, Chinch Bunder, mumbai ( allowed )

only ".....", ",,,,", "----" ( not allowed )


 $("#" + (idOfElement)).on("keypress keyup", function (e) {
                        this.value = this.value
                            //.replace(/[^\..]/g,'')
                            .replace(/(^[\d#\w]+)/g, '$1')
                            .replace(/(\s[1-9A-Za-z\/#-]*)./g, '$1');

                    });

I want the user allowed to enter numbers, '#', '/', '-', space, and alphabets only, and if they enter any other special characters it shouldn't allow them to do so.

code given below is working fine for number with decimal upto two position. similarly i want to do the same for address.

below code allows 12345.67

it doesn't allow 23.4565, 23289.499999

//for numbers with decimal point upto two position
$("#" + (idOfElement)).on("keypress keyup blur", function (e) {
                        this.value = this.value
                            .replace(/[^\d.]/g, '')
                            .replace(/(^[\d]+)([\d]*)/g, '$1')
                            .replace(/(\..*)\./g, '$1')
                            .replace(/(\.[\d]{2})./g, '$1');
                        if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
                            e.preventDefault();
                        }

I also want the user to enter only alphabets with space and numbers only.

sample data: toothpaste 200g ( allowed )

shampoo..( not allowed )

shampoo (with any other special character like !,?,_,~)( not allowed )

Use below code sample. Also please find fiddle for same in comment.

<input type="text" id="addressID">

  $(document).ready(function(){
  $("input").bind('input', function(e) {
  var str = $("#addressID").val();
  var re = new RegExp(/^[ A-Za-z0-9\/#-]*$/g);
  if (re.test(str)) {
          //alert('valid');

    } else {
       alert("Invalid address, only alphanumeric values and '/','#','-' allowed");
       $("#addressID").val($("#addressID").val().slice(0, -1));
    }
});
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM