Special character validation

前端 未结 3 1041
感情败类
感情败类 2020-12-20 08:30

I have some javascript written to validate that a string is alphanumeric but i was just wondering how i could add some code to include hyphens(-) and slash\'s(/) as acceptab

相关标签:
3条回答
  • 2020-12-20 09:06

    Input:

    <input type="text" name="textname" id="tname"  onblur="namefun(this.value)">
    

    Javascript

    function namefun(c) {
      var spch = /[A-z\s]/gi;
      var dig = /[0-9]/g;
      var ln = c.length;
      var j = 1;
      for (var i = 0; i < ln; i++) {
        var k = c.slice(i, j);
        if (spch.test(c) == false || dig.test(c) == true) {
          alert("Invalid name");
          document.getElementById("tname").value = "";
          ln = 0;
          setTimeout(function () {
            tname.focus();
          }, 1);
          //return false;
        }
        j++;
      }
    }
    
    0 讨论(0)
  • 2020-12-20 09:16
    function isValidCharacter(txtTitle) {   
         var title = document.getElementById(txtTitle);
         var regExp = /^[a-zA-Z]*$/
         if (!regExp.test(title.value)) {
            title.value = '';
            return false;
            }
          else {      
               return true;
            }
       }
    
    
    function Validation(){
     var txtTitles = document.getElementById('txtTitle');
      if (isValidCharacter(txtTitles.id) == false) {
       alert("Please enter valid title. No special character allowed.");        
        return false;
      }  
     }
    
    
    
       $("#Btn").unbind("click").click(function () {
            if (Validation() == false) {
    
            }
            else {
                  //success     
            }
       }
    
    0 讨论(0)
  • 2020-12-20 09:19

    Simply add them to the character group. Of course, because both - and / are special characters in this context (/ ends a RegExp, - expresses a range), you'll need to escape them with a preceding \:

    function validateAddress(){
        var TCode = document.getElementById('address').value;
    
        if( /[^a-zA-Z0-9\-\/]/.test( TCode ) ) {
            alert('Input is not alphanumeric');
            return false;
        }
    
        return true;     
    }
    
    0 讨论(0)
提交回复
热议问题