简体   繁体   中英

Validate textarea input for alphanumeric value

I want to validate textarea which is an Address field, it must contains both of letters and numbers, at least 1 number . for example : "Laksda Adisucipto street, no 22A." but when i just type : "Laksda Adisucipto street" (without number) it can show alert "you must enter at least 1 number"

i'm using Twitter Bootstrap and Validator.js here's my code

HTML :

<div class="form-group col-md-12">
                        <label for="address" class="control-label"><span>*</span> <?php echo $this->lang->line('address');?></label>
                        <textarea class="form-control" id="address" rows="5" required name="address" data-error="Address is required"></textarea>
                        <span class="help-block with-errors"></span>
                    </div>

JS :

<script>
$('#address').change(function()  
{  
 var letterNumber = /^[0-9a-zA-Z]+$/;  
if(($('#').value.match(letterNumber))   
{  
 return true;  
}  
else  
{   
 alert("message");   
 return false;   
}  
 }  );

Try this

$('#address').blur(function()  
{  
 var letterNumber = /^[0-9a-zA-Z]+$/;  
    if(this.value.match(letterNumber))   
      {  
       return true;  
      }  
    else  
    {   
     alert("message");   
     return false;   
    }  
 });

you can check it here: http://jsfiddle.net/oa6eewck/

$('#address').blur(function()  
{  
 var letterNumber = /^[0-9a-zA-Z]+$/;  
    if(this.value.match(letterNumber))   
      {  
       return true;  
      }  
    else  
    {   
     alert("message");   
     return false;   
    }  
 });

This function will allow only characters and numbers,it will be good for a input text field but since you are having text area "spaces" and "commas" and "periods" are expected right.

So better follow the expression follows :

    $('#address').blur(function()  
        {  
        var hasNumber    = this.value.match(/^[a-zA-Z0-9\s .,]+$/);
        if ( hasNumber) {
         return true;
        } else {
         alert("message");   
         return false; 
        }
        });
$('#address').on('change', function () {
    var hasNumber = this.value.match(/\d/);
    var isAlfa    = this.value.match(/^[0-9a-zA-Z]+$/);

    if ( hasNumber && isAlfa ) {
        return true;
    } else {
        alert("message");   
        return false; 
    }
});

FIDDLE

adeneo's solution is right. but I think isAlfa should have following value

var isAlfa = this.value.match(/^[A-Za-z\\d(-.,) ]+/);

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