简体   繁体   中英

JavaScript validation for white space

I am doing client side validation in JavaScript. I can do validation for mandatory fields and phone number fields, but except email field all other fields are accepting white space, such that the validation passes and creates a new row of data. How to include white space validation in my code using JavaScript?

JavaScript:

function form_validate(){
    var error = 0;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    $('#form input[type=text]').each(function(n,element){
        $(this).removeClass('warning');
        if ($(element).val()=='') {
            $("#warning td").text("All fields are mandatory.");
            $(this).addClass('warning');
            $("#warning").show();
            error++;
        }else if($(element).attr('name')=='email'){
            if (!emailReg.test($(element).val())){ 
                $("#warning td").text("Enter a valid email address.");
                $(this).addClass('warning');
                $("#warning").show();
                error++;
            }
        }else if(($(element).attr('name')=='phone' || $(element).attr('name')=='mobile') && error==0){
            if (isNaN($(element).val())){
                $("#warning td").text("Enter valid phone number.");
                $(this).addClass('warning');
                $("#warning").show();
                error++;
            }
        }
    });
    if(error){
        return false;
    }else{
        return true;
    }
}

HTML

<table  width="100%">
<tr>
    <td style="width:100px;">First name:</td><td><input type="text" name="first_name" id="first_name" maxlength="20"/></td>
</tr>
<tr>
    <td style="width:100px;">Last name:</td><td><input type="text" name="last_name" id="last_name" maxlength="20"/></td>
</tr>
<tr>
    <td>Email:</td><td><input type="text" name="email" maxlength="36" id="email"/></td>
</tr>
<tr>
    <td>Daytime phone:</td><td><input type="text" name="phone" maxlength="15" id="phone_no" /></td>
</tr>
<tr>
    <td>Mobile phone:</td><td><input type="text" name="mobile" maxlength="15" id="mobile" /></td>
</tr>
<tr style="display:none;color:red" id="warning">
    <td colspan="2" align="center" >All fields are mandatory</td>
</tr>
</table>

Please have a look at http://jsfiddle.net/2W6fk/3/

       function form_validate(){
    var error = 0;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var mobile_no_length = $('#mobile').val().trim().length
           $(".text_field").each(function(n,element){
             $(this).removeClass('warning');
             if ($(element).val().trim().length < 1) {
                $("#warning td").text("All fields are mandatory.");
                $(this).addClass('warning');
                $("#warning").show();
                error++;
             }else if($(element).attr('name')=='email'){
                if (!emailReg.test($(element).val())){ 
                  $("#warning td").text("Enter a valid email address.");
                  $(this).addClass('warning');
                  $("#warning").show();
                   error++;
                }
            }else if(mobile_no_length < 1){
                if (isNaN($(element).val())){
                  $("#warning td").text("Enter valid phone number.");
                  $(this).addClass('warning');
                  $("#warning").show();
                   error++;
                }
            }

           });
           if(error){
                return false;
           }else{
                return true;
           }
    }

$('input[type=button]').on("click",function(){
    form_validate();
});

$("#mobile, #phone_no").on("keyup", function(event) {
    var limitField = $(this).val().trim().length;
        var limit = "12"
        this.value = this.value.replace(/[^0-9_\-\.]/g, '');
        var id = $(this).attr('id')
    if (limitField > limit) {
            $("#"+id).val($(this).val().trim().substring(0, limit));
        }
});

Note: I added text_field class except email and phone. Now i am validating the both #mobile, #phone_no . Now you can't type characters in that field ( You can type only integers ). And then I am allowing phone number up to 12 digits . Please change it as per your requirement. If you don't want to validate #phone_no please remove from validation.

Am I missed any other validation?

This is regex i use for simple email validation

/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}/g

As you can see, there is a check for upper and lower cases and numbers and some other characters. the final group accepts 2 to 6 characters since there are some domain extensions like .travel ect.

EDIT: it will also fail if email is empty http://jsfiddle.net/VjDFr/

$(document).ready(function(){
    var reg = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}/
    alert(reg.test($('#f').val()));
});

Javascript does not have a native trim() function, but you can easily extend the String 's prototype to define one:

String.prototype.trim = function ()
{
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
}

That way you can just call trim() on any Javascript string you have, like:

var s = '   This is a string!  ';
alert(s.trim()); // Alerts: "This is a string!"

And since you're using jQuery, you can also just use:

$.trim(yourString);

Hope this helps.

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