简体   繁体   English

表单验证,计算javascript中字符串的最小值和最大值

[英]Form validation, count min and max of string in javascript

I am new in java script, can any body help. 我是Java脚本的新手,任何机构都可以帮忙。

This code is to validate whether the userid is available in database and works fine for me. 此代码用于验证用户标识在数据库中是否可用并且对我而言工作正常。 But I also need to validate the min and max length of the string when user enter the user id. 但是当用户输入用户ID时,我还需要验证字符串的最小和最大长度。

<input type="text" id="userid" name="userid" class="form-control" data-required="true" onblur="return check_userexist();">
    <div id="InfoUsername"></div>



 function check_userexist(){

        var username = $("#userid").val();
        if(username.length > 0){
            $.post("/users/validator/check_username.php", {
                username: $('#userid').val(),
            }, function(response){
                 $('#InfoUsername').fadeOut();
                setTimeout("finishAjax('InfoUsername', '"+escape(response)+"')", 100);
            });
            return false;
        }
    }

php code : PHP代码:

if($_REQUEST)
{
    $user   = $_REQUEST['userid'];
    if ($users->CountUsernameExist($user) >0) {
    echo 'Not Available!';
    }else{
    echo 'Ok available';
    } ;     
}   
if(username.length >= MIN_LENGTH && username.length <= MAX_LENGTH){
    //allright

Here we've checking MIN and MAX length of value of username 在这里,我们检查了用户名值的MIN和MAX长度

Check min & max length in if condition. 检查最小和最大长度if条件。 Exampe 例子

if(username.length > min_val && username.length <= max_val){
    //Your codes
}else{
    //alert('Your alert message to user!');
    $('#InfoUsername').html('<span style="color: #f00;">Your alert message to user</span>');
    //or
    //$('#InfoUsername').text('Your alert message to user');
}

There is a pure html5 solution for this, not using javascript. 有一个纯html5解决方案,不使用javascript。 You can use the pattern attribute as below, where min, max are the 2 boundary numbers: 您可以如下使用pattern属性,其中min,max是2个边界数字:

 <input type="text" id="userid" name="userid" pattern=".{min,max}" required 
class="form-control" data-required="true" onblur="return check_userexist();">

See pattern attribute 查看图案属性

Remember checking also in the php side, just in case Javascript is disable So use: 记住还要在php端进行检查,以防万一禁用Javascript,请使用:

if(username.length > 0 && username.length <= ANY_VALUE) {

/* ALSO ADD THIS IN PHP */
if ( strlen($user) > 0 || strlen($user) < ANY_VALUE )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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